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

interface CreateRoleInput {
  name: string;
  description?: string;
}

/**
 * Function: createRole
 *
 * Creates a new role with the specified name.
 * Validates that the name is unique within the system.
 */
export async function run<CF extends Record<string, unknown>>(
  db: Transaction,
  input: CreateRoleInput & CF,
) {
  const { name, description, ...customFields } = input;

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

  const existingRole = await db
    .selectFrom("Role")
    .selectAll()
    .where("name", "=", name)
    .forUpdate()
    .executeTakeFirst();

  if (existingRole) {
    return err(new DuplicateRoleNameError(name));
  }

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

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