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

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

export function createChannelOrderLineType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateChannelOrderLineTypeParams<F>,
) {
  return db
    .type("ChannelOrderLine", {
      channelOrderId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.channelOrderType ?? 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: params.listingType ?? listing },
          backward: "channelOrderLines",
        })
        .description("Optional mapped Listing"),
      itemId: db
        .uuid({ optional: true })
        .relation({
          type: "n-1",
          toward: { type: params.itemType ?? itemStub },
          backward: "channelOrderLines",
        })
        .description("Optional resolved Item"),
      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: db
        .uuid({ optional: true })
        .relation({
          type: "n-1",
          toward: { type: params.currencyType ?? currencyStub },
          backward: "channelOrderLines",
        })
        .description("Optional mapped currency"),
      unitId: db
        .uuid({ optional: true })
        .relation({
          type: "n-1",
          toward: { type: params.unitType ?? unitStub },
          backward: "channelOrderLines",
        })
        .description("Optional mapped unit of measure"),
      rawPayload: db
        .string({ optional: true })
        .description("Optional serialized normalized line payload"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const channelOrderLine = createChannelOrderLineType({});
