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

export const LISTING_STATUSES: [string, string, string, string] = [
  "DRAFT",
  "ACTIVE",
  "PAUSED",
  "RETIRED",
];

export interface CreateListingTypeParams<F extends Record<string, TailorAnyDBField>> {
  fields?: F;
  companyType?: TailorAnyDBType;
  channelType?: TailorAnyDBType;
  itemType?: TailorAnyDBType;
  salesPriceListType?: TailorAnyDBType;
}

export function createListingType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateListingTypeParams<F>,
) {
  return db
    .type("Listing", {
      companyId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.companyType ?? companyStub },
          backward: "listings",
        })
        .description("Foreign key to Company"),
      channelId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.channelType ?? channel },
          backward: "listings",
        })
        .description("Foreign key to Channel"),
      itemId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.itemType ?? itemStub },
          backward: "listings",
        })
        .description("Foreign key to Item"),
      sku: db.string({ optional: true }).description("Optional internal listing SKU"),
      externalIdentifier: db.string({ optional: true }).description("External listing identifier"),
      title: db.string({ optional: true }).description("Listing title"),
      status: db.enum(LISTING_STATUSES).description("Listing lifecycle status"),
      requiresPriceSync: db.bool().description("Whether active pricing linkage is required"),
      salesPriceListId: db
        .uuid({ optional: true })
        .relation({
          type: "n-1",
          toward: { type: params.salesPriceListType ?? salesPriceList },
          backward: "listings",
        })
        .description("Optional linked SalesPriceList"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .indexes({
      fields: ["channelId", "externalIdentifier"],
      unique: true,
      name: "listing_channel_external_identifier_idx",
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const listing = createListingType({});
