import {
  type CommonReservedFields,
  type NoReservedFields,
  defaultGqlPermission,
  defaultPermission,
} from "@tailor-platform/erp-kit/core";
import { db, type TailorAnyDBField } from "@tailor-platform/sdk";
import { roleLifecycle } from "./role.lifecycle.generated";

const builtins = {
  name: db.string().unique().description("Role name (unique identifier)"),
  description: db
    .string({ optional: true })
    .description("Optional description of what this role represents"),
  status: db.enum(roleLifecycle.states).description("Role status (ACTIVE or INACTIVE)"),
  permissions: db
    .string({ array: true, optional: true })
    .description("Array of permission keys in module:scope:command format"),
};

type ReservedFields = keyof typeof builtins | CommonReservedFields;

export interface CreateRoleTypeParams<F extends Record<string, TailorAnyDBField>> {
  fields?: NoReservedFields<F, ReservedFields>;
}

export function createRoleType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateRoleTypeParams<F>,
) {
  return db
    .type("Role", {
      ...builtins,
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const role = createRoleType({});
