package permission

import (
	"context"
	"fmt"

	"go.b0esche.cloud/backend/internal/database"

	"github.com/google/uuid"
)

type Permission string

const (
	FileRead     Permission = "file.read"
	FileWrite    Permission = "file.write"
	FileDelete   Permission = "file.delete"
	DocumentView Permission = "document.view"
	DocumentEdit Permission = "document.edit"
	OrgManage    Permission = "org.manage"
)

var rolePermissions = map[string][]Permission{
	"owner":  {FileRead, FileWrite, FileDelete, DocumentView, DocumentEdit, OrgManage},
	"admin":  {FileRead, FileWrite, FileDelete, DocumentView, DocumentEdit},
	"editor": {FileRead, FileWrite, DocumentView, DocumentEdit},
	"viewer": {FileRead, DocumentView},
}

// HasPermission checks if user has permission in org
func HasPermission(ctx context.Context, db *database.DB, userID, orgID uuid.UUID, perm Permission) (bool, error) {
	membership, err := db.GetUserMembership(ctx, userID, orgID)
	if err != nil {
		return false, err
	}

	perms, ok := rolePermissions[membership.Role]
	if !ok {
		return false, fmt.Errorf("unknown role: %s", membership.Role)
	}

	for _, p := range perms {
		if p == perm {
			return true, nil
		}
	}
	return false, nil
}
