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

export const PURCHASE_BILL_STATUSES: [string, string, string, string] = [
  "DRAFT",
  "BLOCKED",
  "MATCHED",
  "CANCELLED",
];

export interface CreatePurchaseBillTypeParams<F extends Record<string, TailorAnyDBField>> {
  fields?: F;
  companyType?: TailorAnyDBType;
  supplierType?: TailorAnyDBType;
}

export function createPurchaseBillType<const F extends Record<string, TailorAnyDBField>>(
  params: CreatePurchaseBillTypeParams<F>,
) {
  return db
    .type("PurchaseBill", {
      companyId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.companyType ?? companyStub },
          backward: "purchaseBills",
        })
        .description("Foreign key to Company"),
      supplierId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.supplierType ?? businessPartnerStub },
          backward: "purchaseBills",
        })
        .description("Foreign key to supplier BusinessPartner"),
      invoiceNumber: db.string().description("Supplier invoice number"),
      invoiceDate: db.date().description("Supplier invoice date"),
      status: db.enum(PURCHASE_BILL_STATUSES).description("Purchase-bill lifecycle status"),
      lines: db.string().description("Serialized purchase-bill line collection"),
      paymentTermSnapshot: db
        .string({ optional: true })
        .description("Serialized immutable payment-term snapshot"),
      supplierTaxIdentification: db
        .string({ optional: true })
        .description("Snapshotted supplier tax identification"),
      matchingMode: db.string({ optional: true }).description("Recorded matching mode"),
      varianceReason: db.string({ optional: true }).description("Blocked variance reason"),
      releaseReason: db.string({ optional: true }).description("Release override reason"),
      dueSchedule: db.string({ optional: true }).description("Serialized payable due schedule"),
      downstreamAccepted: db
        .bool()
        .description("Whether downstream AP or accounting accepted the handoff"),
      comparisonEvidence: db
        .string({ optional: true })
        .description("Serialized matching evidence and comparison basis"),
      billReadyHandoff: db
        .string({ optional: true })
        .description("Serialized downstream bill-ready handoff"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const purchaseBill = createPurchaseBillType({});
