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

const builtins = {
  email: db.string().unique().description("User email address (unique identifier)"),
  name: db.string().description("User display name"),
  status: db.enum(userLifecycle.states).description("User status"),
  permissions: db
    .string({ array: true, optional: true })
    .description("Flattened permission keys from all assigned roles"),
};

type ReservedFields = keyof typeof builtins | CommonReservedFields;

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

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

export const user = createUserType({});
