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 const MATCHING_MODES: [string, string] = ["TWO_WAY", "THREE_WAY"];

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 },
          backward: "purchaseBills",
        })
        .description("Foreign key to Company"),
      supplierId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.supplierType },
          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"),
      paymentTermSnapshotLines: db
        .object(
          {
            kind: db.string({ optional: true }),
            days: db.int({ optional: true }),
            fixedDayOfMonth: db.int({ optional: true }),
            percentage: db.decimal({ optional: true }),
            fixedAmount: db.decimal({ optional: true }),
            note: db.string({ optional: true }),
          },
          { optional: true, array: true },
        )
        .description("Snapshotted payment-term schedule lines at snapshot time"),
      supplierTaxIdentification: db
        .string({ optional: true })
        .description("Snapshotted supplier tax identification"),
      matchingMode: db
        .enum(MATCHING_MODES, { 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
        .object(
          {
            dueDate: db.date(),
            amount: db.decimal(),
          },
          { optional: true, array: true },
        )
        .description("Computed payable due schedule lines"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const purchaseBill = createPurchaseBillType({
  companyType: companyStub,
  supplierType: businessPartnerStub,
});
