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

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

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

export function createRoutingType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateRoutingTypeParams<F>,
) {
  return db
    .type("Routing", {
      parentItemId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.itemType },
          backward: "routings",
        })
        .description("Foreign key to Item – the manufactured item"),
      companyId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.companyType },
          backward: "routings",
        })
        .description("Foreign key to Company"),
      siteId: db
        .uuid({ optional: true })
        .relation({
          type: "n-1",
          toward: { type: params.siteType },
          backward: "routings",
        })
        .description("Foreign key to Site – optional site scope"),
      revisionNumber: db.string({ optional: true }).description("Version identity of the routing"),
      status: db
        .enum([...BASE_ROUTING_STATUSES] as [string, ...string[]])
        .description("Lifecycle status: DRAFT, ACTIVE, INACTIVE"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const routing = createRoutingType({
  companyType: companyStub,
  siteType: siteStub,
  itemType: itemStub,
});
