import { Transaction } from "../generated/kysely-tailordb";
import {
  DuplicatePermissionKeyError,
  InvalidPermissionKeyFormatError,
  MissingRequiredFieldError,
} from "../lib/errors.generated";
import { ok, err } from "@tailor-platform/erp-kit/module";

interface CreatePermissionInput {
  key: string;
  description?: string;
}

const PERMISSION_KEY_PATTERN = /^[a-zA-Z0-9_-]+:[a-zA-Z0-9_-]+$/;

/**
 * Function: createPermission
 *
 * Creates a new permission with the specified key in resource:action format.
 * Validates that the key follows the correct format and is unique.
 */
export async function run<CF extends Record<string, unknown>>(
  db: Transaction,
  input: CreatePermissionInput & CF,
) {
  const { key, description, ...customFields } = input;

  if (!key || key.trim() === "") {
    return err(new MissingRequiredFieldError("key"));
  }

  if (!PERMISSION_KEY_PATTERN.test(key)) {
    return err(new InvalidPermissionKeyFormatError(key));
  }

  const existingPermission = await db
    .selectFrom("Permission")
    .selectAll()
    .where("key", "=", key)
    .forUpdate()
    .executeTakeFirst();

  if (existingPermission) {
    return err(new DuplicatePermissionKeyError(key));
  }

  // 4. Create permission
  const permission = await db
    .insertInto("Permission")
    .values({
      ...(customFields as Record<string, unknown>),
      key,
      description: description ?? null,
      createdAt: new Date(),
      updatedAt: null,
    })
    .returningAll()
    .executeTakeFirst();

  return ok({ permission: permission! });
}
