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

export const SALES_PRICE_LIST_STATUSES: [string, string, string] = ["DRAFT", "ACTIVE", "INACTIVE"];

export interface CreateSalesPriceListTypeParams<F extends Record<string, TailorAnyDBField>> {
  fields?: F;
  companyType?: TailorAnyDBType;
  customerType?: TailorAnyDBType;
  channelType?: TailorAnyDBType;
}

export function createSalesPriceListType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateSalesPriceListTypeParams<F>,
) {
  return db
    .type("SalesPriceList", {
      companyId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.companyType ?? companyStub },
          backward: "salesPriceLists",
        })
        .description("Foreign key to Company"),
      customerId: db
        .uuid({ optional: true })
        .relation({
          type: "n-1",
          toward: { type: params.customerType ?? businessPartnerStub },
          backward: "salesPriceLists",
        })
        .description("Optional scoped customer"),
      channelId: db
        .uuid({ optional: true })
        .relation({
          type: "n-1",
          toward: { type: params.channelType ?? channel },
          backward: "salesPriceLists",
        })
        .description("Optional scoped channel"),
      name: db.string().description("Price-list name"),
      code: db.string({ optional: true }).description("Optional price-list code"),
      priority: db.int().description("List precedence priority"),
      status: db.enum(SALES_PRICE_LIST_STATUSES).description("Price-list lifecycle status"),
      notes: db.string({ optional: true }).description("Optional notes"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const salesPriceList = createSalesPriceListType({});
