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

export const PROFIT_CENTER_STATUSES = ["DRAFT", "ACTIVE", "INACTIVE"] as const;

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

export function createProfitCenterType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateProfitCenterTypeParams<F>,
) {
  return db
    .type("ProfitCenter", {
      code: db.string().description("Profit center code"),
      name: db.string().description("Profit center name"),
      description: db.string({ optional: true }).description("Profit center description"),
      responsiblePersonId: db
        .uuid({ optional: true })
        .relation({
          type: "n-1",
          toward: { type: params.userType ?? userStub },
          backward: "responsibleProfitCenters",
        })
        .description("Foreign key to User"),
      companyId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.companyType ?? companyStub },
          backward: "profitCenters",
        })
        .description("Foreign key to Company"),
      validFrom: db.date().description("Valid from date"),
      validTo: db.date({ optional: true }).description("Valid to date"),
      status: db.enum([...PROFIT_CENTER_STATUSES]).description("Profit center lifecycle status"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const profitCenter = createProfitCenterType({});
