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

const builtins = (params: { companyType?: TailorAnyDBType; itemType?: TailorAnyDBType }) => {
  const companyId = db.uuid().description("Foreign key to Company");
  const itemId = db.uuid().description("Foreign key to Item");
  return {
    companyId: params.companyType
      ? companyId.relation({
          type: "n-1",
          toward: { type: params.companyType },
          backward: "listings",
        })
      : companyId,
    channelId: db
      .uuid()
      .relation({
        type: "n-1",
        toward: { type: channel },
        backward: "listings",
      })
      .description("Foreign key to Channel"),
    itemId: params.itemType
      ? itemId.relation({
          type: "n-1",
          toward: { type: params.itemType },
          backward: "listings",
        })
      : itemId,
    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(listingLifecycle.states).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: salesPriceList },
        backward: "listings",
      })
      .description("Optional linked SalesPriceList"),
  };
};

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

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

export function createListingType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateListingTypeParams<F>,
) {
  return db
    .type("Listing", {
      ...builtins(params),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .indexes({
      fields: ["channelId", "externalIdentifier"],
      unique: true,
      name: "listing_channel_external_identifier_idx",
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const listing = createListingType({});
