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

const builtins = {
  code: db.string().description("Department code, unique per company"),
  name: db.string().description("Department display name"),
  companyId: db
    .uuid()
    .relation({
      type: "n-1",
      toward: { type: company },
      backward: "departments",
    })
    .description("Foreign key to Company"),
  parentDepartmentId: db
    .uuid({ optional: true })
    .relation({
      type: "n-1",
      toward: { type: "self" },
      backward: "childDepartments",
    })
    .description("Foreign key to parent Department for hierarchy"),
  status: db.enum(departmentLifecycle.states).description("Lifecycle status"),
};

type ReservedFields = keyof typeof builtins | CommonReservedFields;

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

export function createDepartmentType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateDepartmentTypeParams<F>,
) {
  const departmentType = db
    .type("Department", {
      ...builtins,
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);

  return departmentType;
}

export const department = createDepartmentType({});
