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 { salesOrderLifecycle } from "./salesOrder.lifecycle.generated";
import { salesPaymentTerm } from "./salesPaymentTerm";

const builtins = (params: { companyType?: TailorAnyDBType; customerType?: TailorAnyDBType }) => {
  const companyId = db.uuid().description("Foreign key to Company");
  const customerId = db.uuid().description("Foreign key to Customer");
  return {
    companyId: params.companyType
      ? companyId.relation({
          type: "n-1",
          toward: { type: params.companyType },
          backward: "salesOrders",
        })
      : companyId,
    customerId: params.customerType
      ? customerId.relation({
          type: "n-1",
          toward: { type: params.customerType },
          backward: "salesOrders",
        })
      : customerId,
    channelId: db
      .uuid({ optional: true })
      .relation({
        type: "n-1",
        toward: { type: channel },
        backward: "salesOrders",
      })
      .description("Optional channel"),
    paymentTermId: db
      .uuid({ optional: true })
      .relation({
        type: "n-1",
        toward: { type: salesPaymentTerm },
        backward: "salesOrders",
      })
      .description("Optional payment term"),
    status: db.enum(salesOrderLifecycle.states).description("Sales-order lifecycle status"),
    orderDate: db.date().description("Order date"),
    requestedShipDate: db.date({ optional: true }).description("Optional requested ship date"),
    shippingAddressSnapshot: db
      .string({ optional: true })
      .description("Serialized shipping address snapshot"),
    billingAddressSnapshot: db
      .string({ optional: true })
      .description("Serialized billing address snapshot"),
    paymentTermSnapshot: db
      .string({ optional: true })
      .description("Serialized payment-term snapshot"),
    rejectionReason: db.string({ optional: true }).description("Latest rejection reason"),
    holdReason: db.string({ optional: true }).description("Latest credit-hold reason"),
    closeReason: db.string({ optional: true }).description("Close reason"),
  };
};

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

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

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

export const salesOrder = createSalesOrderType({});
