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

export const OVERHEAD_ABSORPTION_METHODS = [
  "PERCENT_OF_LABOR_COST",
  "PERCENT_OF_MACHINE_COST",
  "FIXED_AMOUNT_PER_GOOD_UNIT",
] as const;

const builtins = (params: { companyType?: TailorAnyDBType; siteType?: TailorAnyDBType }) => {
  const companyId = db.uuid().description("Foreign key to Company");
  const siteId = db
    .uuid({ optional: true })
    .description("Foreign key to Site; required when company uses site-level work centers");
  return {
    code: db.string().description("Work-center code, unique within company and site scope"),
    companyId: params.companyType
      ? companyId.relation({
          type: "n-1",
          toward: { type: params.companyType },
          backward: "workCenters",
        })
      : companyId,
    siteId: params.siteType
      ? siteId.relation({
          type: "n-1",
          toward: { type: params.siteType },
          backward: "workCenters",
        })
      : siteId,
    status: db
      .enum(workCenterLifecycle.states)
      .description("Lifecycle status: DRAFT, ACTIVE, INACTIVE"),
    capacityAssumptions: db
      .float()
      .description("Capacity assumption expressed in a consistent planning unit; must be positive"),
    laborRate: db
      .float({ optional: true })
      .description("Standard labor rate per planning unit; must be zero or greater"),
    machineRate: db
      .float({ optional: true })
      .description("Standard machine rate per planning unit; must be zero or greater"),
    calendarReference: db
      .string({ optional: true })
      .description("Calendar identifier; required when activating the work center"),
    overheadAbsorptionMethod: db
      .enum(OVERHEAD_ABSORPTION_METHODS, {
        optional: true,
      })
      .description(
        "Method for absorbing overhead: PERCENT_OF_LABOR_COST, PERCENT_OF_MACHINE_COST, or FIXED_AMOUNT_PER_GOOD_UNIT",
      ),
    overheadAbsorptionCurrency: db
      .string({ optional: true })
      .description(
        "ISO 4217 currency code for overhead absorption; required when method is FIXED_AMOUNT_PER_GOOD_UNIT",
      ),
  };
};

type ReservedFields = keyof ReturnType<typeof builtins> | CommonReservedFields;

export interface CreateWorkCenterTypeParams<F extends Record<string, TailorAnyDBField>> {
  fields?: NoReservedFields<F, ReservedFields>;
  companyType?: TailorAnyDBType;
  siteType?: TailorAnyDBType;
}

export function createWorkCenterType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateWorkCenterTypeParams<F>,
) {
  return db
    .type("WorkCenter", {
      ...builtins(params),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .indexes({
      fields: ["code", "companyId", "siteId"],
      unique: true,
      name: "work_center_code_company_site_idx",
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const workCenter = createWorkCenterType({});
