import {
  db,
  type TailorAnyDBField,
  type TailorAnyDBType,
  unsafeAllowAllGqlPermission,
  unsafeAllowAllTypePermission,
} from "@tailor-platform/sdk";
import {
  company as companyStub,
  department as departmentStub,
  user as userStub,
} from "../lib/_db_deps";
import { costCenterHierarchyNode } from "./costCenterHierarchyNode";

export interface CreateCostCenterTypeParams<F extends Record<string, TailorAnyDBField>> {
  fields?: F;
  companyType?: TailorAnyDBType;
  costCenterHierarchyNodeType?: TailorAnyDBType;
  userType?: TailorAnyDBType;
  departmentType?: TailorAnyDBType;
}

export function createCostCenterType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateCostCenterTypeParams<F>,
) {
  return db
    .type("CostCenter", {
      code: db.string().description("Cost center code"),
      name: db.string().description("Cost center name"),
      description: db.string({ optional: true }).description("Cost center description"),
      category: db.string().description("Cost center category"),
      responsiblePersonId: db
        .uuid({ optional: true })
        .relation({
          type: "n-1",
          toward: { type: params.userType ?? userStub },
          backward: "responsibleCostCenters",
        })
        .description("Foreign key to User"),
      departmentId: db
        .uuid({ optional: true })
        .relation({
          type: "n-1",
          toward: { type: params.departmentType ?? departmentStub },
          backward: "costCenters",
        })
        .description("Foreign key to Department"),
      companyId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.companyType ?? companyStub },
          backward: "costCenters",
        })
        .description("Foreign key to Company"),
      hierarchyNodeId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.costCenterHierarchyNodeType ?? costCenterHierarchyNode },
          backward: "costCenters",
        })
        .description("Foreign key to CostCenterHierarchyNode"),
      validFrom: db.date().description("Valid from date"),
      validTo: db.date({ optional: true }).description("Valid to date"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const costCenter = createCostCenterType({});
