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

export const INTERNAL_ORDER_STATUSES = [
  "CREATED",
  "RELEASED",
  "TECHNICALLY_COMPLETED",
  "CLOSED",
] as const;

export const INTERNAL_ORDER_TYPES = ["OVERHEAD", "INVESTMENT", "ACCRUAL"] as const;

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

export function createInternalOrderType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateInternalOrderTypeParams<F>,
) {
  return db
    .type("InternalOrder", {
      orderNumber: db.string().description("Internal order number"),
      orderType: db.enum([...INTERNAL_ORDER_TYPES]).description("Internal order type"),
      description: db.string().description("Internal order description"),
      responsiblePersonId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.userType ?? userStub },
          backward: "responsibleInternalOrders",
        })
        .description("Foreign key to User"),
      costCenterId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.costCenterType ?? costCenter },
          backward: "internalOrders",
        })
        .description("Foreign key to CostCenter"),
      companyId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.companyType ?? companyStub },
          backward: "internalOrders",
        })
        .description("Foreign key to Company"),
      validFrom: db.date({ optional: true }).description("Valid from date"),
      validTo: db.date({ optional: true }).description("Valid to date"),
      status: db.enum([...INTERNAL_ORDER_STATUSES]).description("Internal order lifecycle status"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const internalOrder = createInternalOrderType({});
