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

const builtins = (params: {
  itemType?: TailorAnyDBType;
  currencyType?: TailorAnyDBType;
  unitType?: TailorAnyDBType;
}) => {
  const itemId = db.uuid().description("Foreign key to Item");
  const currencyId = db.uuid().description("Foreign key to Currency");
  const unitId = db.uuid({ optional: true }).description("Optional unit");
  return {
    salesOrderId: db
      .uuid()
      .relation({
        type: "n-1",
        toward: { type: salesOrder },
        backward: "lines",
      })
      .description("Foreign key to SalesOrder"),
    itemId: params.itemType
      ? itemId.relation({
          type: "n-1",
          toward: { type: params.itemType },
          backward: "salesOrderLines",
        })
      : itemId,
    description: db.string({ optional: true }).description("Optional line description"),
    quantity: db.float().description("Ordered quantity"),
    unitPrice: db.float().description("Unit price"),
    currencyId: params.currencyType
      ? currencyId.relation({
          type: "n-1",
          toward: { type: params.currencyType },
          backward: "salesOrderLines",
        })
      : currencyId,
    unitId: params.unitType
      ? unitId.relation({
          type: "n-1",
          toward: { type: params.unitType },
          backward: "salesOrderLines",
        })
      : unitId,
    matchedPriceRuleId: db
      .uuid({ optional: true })
      .relation({
        type: "n-1",
        toward: { type: salesPriceRule },
        backward: "salesOrderLines",
      })
      .description("Optional matched SalesPriceRule"),
    billingPolicy: db.string({ optional: true }).description("ORDER or SHIPMENT"),
    requestedShipDate: db.date({ optional: true }).description("Requested ship date"),
    requiresPhysicalFulfillment: db.bool().description("Whether physical shipment is required"),
    priceSnapshot: db.string({ optional: true }).description("Serialized price snapshot"),
    shippedQuantity: db.float().description("Cumulative shipped quantity"),
    invoicedQuantity: db.float().description("Cumulative invoiced quantity"),
  };
};

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

export interface CreateSalesOrderLineTypeParams<F extends Record<string, TailorAnyDBField>> {
  fields?: NoReservedFields<F, ReservedFields>;
  itemType?: TailorAnyDBType;
  currencyType?: TailorAnyDBType;
  unitType?: TailorAnyDBType;
}

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

export const salesOrderLine = createSalesOrderLineType({});
