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

const builtins = (params: {
  itemType?: TailorAnyDBType;
  currencyType?: TailorAnyDBType;
  unitType?: TailorAnyDBType;
}) => {
  const itemId = db.uuid({ optional: true }).description("Optional resolved Item");
  const currencyId = db.uuid({ optional: true }).description("Optional mapped currency");
  const unitId = db.uuid({ optional: true }).description("Optional mapped unit of measure");
  return {
    channelOrderId: db
      .uuid()
      .relation({
        type: "n-1",
        toward: { type: channelOrder },
        backward: "lines",
      })
      .description("Foreign key to ChannelOrder"),
    externalLineId: db.string({ optional: true }).description("Optional external line identifier"),
    listingId: db
      .uuid({ optional: true })
      .relation({
        type: "n-1",
        toward: { type: listing },
        backward: "channelOrderLines",
      })
      .description("Optional mapped Listing"),
    itemId: params.itemType
      ? itemId.relation({
          type: "n-1",
          toward: { type: params.itemType },
          backward: "channelOrderLines",
        })
      : itemId,
    description: db.string({ optional: true }).description("Optional normalized line description"),
    quantity: db.float().description("Normalized ordered quantity"),
    unitPrice: db.float({ optional: true }).description("Optional normalized unit price"),
    currencyId: params.currencyType
      ? currencyId.relation({
          type: "n-1",
          toward: { type: params.currencyType },
          backward: "channelOrderLines",
        })
      : currencyId,
    unitId: params.unitType
      ? unitId.relation({
          type: "n-1",
          toward: { type: params.unitType },
          backward: "channelOrderLines",
        })
      : unitId,
    rawPayload: db
      .string({ optional: true })
      .description("Optional serialized normalized line payload"),
  };
};

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

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

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

export const channelOrderLine = createChannelOrderLineType({});
