import {
  db,
  type TailorAnyDBField,
  unsafeAllowAllGqlPermission,
  unsafeAllowAllTypePermission,
} from "@tailor-platform/sdk";
import { company } from "./company";

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

export function createDepartmentType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateDepartmentTypeParams<F>,
) {
  const departmentType = db
    .type("Department", {
      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.string().description("Department lifecycle status: ACTIVE, INACTIVE"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);

  return departmentType;
}

export const department = createDepartmentType({});
