import {
  db,
  type TailorAnyDBField,
  type TailorAnyDBType,
  unsafeAllowAllGqlPermission,
  unsafeAllowAllTypePermission,
} from "@tailor-platform/sdk";
import { unit as unitStub } from "../lib/_db_deps";

export const BASE_PRODUCT_STATUSES = ["DRAFT", "ACTIVE", "ARCHIVED"] as const;

export interface CreateProductTypeParams<F extends Record<string, TailorAnyDBField>> {
  fields?: F;
  additionalStatuses?: string[];
  unitType: TailorAnyDBType;
}

export function createProductType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateProductTypeParams<F>,
) {
  const statuses = [...BASE_PRODUCT_STATUSES, ...(params.additionalStatuses ?? [])] as [
    string,
    ...string[],
  ];

  return db
    .type("Product", {
      code: db.string().unique().description("Globally unique, immutable product code"),
      name: db.string().description("Product display name"),
      description: db.string({ optional: true }).description("Optional product description"),
      unitId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.unitType },
          backward: "products",
        })
        .description("Foreign key to Unit"),
      status: db.enum(statuses).description("Lifecycle status: DRAFT, ACTIVE, ARCHIVED"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const product = createProductType({ unitType: unitStub });
