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

const builtins = (params: {
  companyType?: TailorAnyDBType;
  siteType?: TailorAnyDBType;
  itemType?: TailorAnyDBType;
}) => {
  const parentItemId = db.uuid().description("Foreign key to Item – the manufactured item");
  const companyId = db.uuid().description("Foreign key to Company");
  const siteId = db
    .uuid({ optional: true })
    .description("Foreign key to Site – optional site scope");
  return {
    parentItemId: params.itemType
      ? parentItemId.relation({
          type: "n-1",
          toward: { type: params.itemType },
          backward: "routings",
        })
      : parentItemId,
    companyId: params.companyType
      ? companyId.relation({
          type: "n-1",
          toward: { type: params.companyType },
          backward: "routings",
        })
      : companyId,
    siteId: params.siteType
      ? siteId.relation({
          type: "n-1",
          toward: { type: params.siteType },
          backward: "routings",
        })
      : siteId,
    revisionNumber: db.string({ optional: true }).description("Version identity of the routing"),
    status: db
      .enum(routingLifecycle.states)
      .description("Lifecycle status: DRAFT, ACTIVE, INACTIVE"),
  };
};

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

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

export function createRoutingType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateRoutingTypeParams<F>,
) {
  return db
    .type("Routing", {
      ...builtins(params),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const routing = createRoutingType({});
