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

export const CHANNEL_ORDER_STATUSES: [string, string, string, string] = [
  "PENDING_CONVERSION",
  "CONVERTED",
  "EXCEPTION",
  "CANCELLED_BY_CHANNEL",
];

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

export function createChannelOrderType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateChannelOrderTypeParams<F>,
) {
  return db
    .type("ChannelOrder", {
      companyId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.companyType ?? companyStub },
          backward: "channelOrders",
        })
        .description("Foreign key to Company"),
      channelId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.channelType ?? channel },
          backward: "channelOrders",
        })
        .description("Foreign key to Channel"),
      externalOrderId: db.string().description("External order identifier"),
      externalCustomerId: db.string({ optional: true }).description("External buyer identifier"),
      customerId: db
        .uuid({ optional: true })
        .relation({
          type: "n-1",
          toward: { type: params.customerType ?? businessPartnerStub },
          backward: "channelOrders",
        })
        .description("Optional mapped customer"),
      salesOrderId: db
        .uuid({ optional: true })
        .relation({
          type: "n-1",
          toward: { type: params.salesOrderType ?? salesOrder },
          backward: "channelOrders",
        })
        .description("Optional linked SalesOrder"),
      status: db.enum(CHANNEL_ORDER_STATUSES).description("Channel-order lifecycle status"),
      orderDate: db.date({ optional: true }).description("Channel order date"),
      currencyId: db
        .uuid({ optional: true })
        .relation({
          type: "n-1",
          toward: { type: params.currencyType ?? currencyStub },
          backward: "channelOrders",
        })
        .description("Optional mapped currency"),
      rawPayload: db.string({ optional: true }).description("Serialized raw inbound payload"),
      normalizedPayload: db
        .string({ optional: true })
        .description("Serialized normalized channel-order payload"),
      errorSummary: db.string({ optional: true }).description("Latest exception summary"),
      retryContext: db.string({ optional: true }).description("Serialized retry context"),
      syncJobId: db
        .uuid({ optional: true })
        .relation({
          type: "n-1",
          toward: { type: params.syncJobType ?? syncJob },
          backward: "channelOrders",
        })
        .description("Optional originating SyncJob"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .indexes({
      fields: ["companyId", "channelId", "externalOrderId"],
      unique: true,
      name: "channel_order_company_channel_external_idx",
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const channelOrder = createChannelOrderType({});
