import {
  db,
  type TailorAnyDBField,
  unsafeAllowAllGqlPermission,
  unsafeAllowAllTypePermission,
} from "@tailor-platform/sdk";
import { businessPartner } from "./businessPartner";

export const IDENTIFICATION_TYPES = [
  "TAX_ID",
  "VAT",
  "DUNS",
  "COMPANY_REGISTRY",
  "NATIONAL_ID",
  "OTHER",
] as const;

export interface CreatePartnerIdentificationTypeParams<F extends Record<string, TailorAnyDBField>> {
  fields?: F;
}

export function createPartnerIdentificationType<const F extends Record<string, TailorAnyDBField>>(
  params: CreatePartnerIdentificationTypeParams<F>,
) {
  return db
    .type("PartnerIdentification", {
      partnerId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: businessPartner },
          backward: "partnerIdentifications",
        })
        .description("Foreign key to BusinessPartner"),
      type: db
        .enum(["TAX_ID", "VAT", "DUNS", "COMPANY_REGISTRY", "NATIONAL_ID", "OTHER"])
        .description(
          "Identification type: TAX_ID, VAT, DUNS, COMPANY_REGISTRY, NATIONAL_ID, OTHER",
        ),
      value: db.string().description("Identification value (e.g., tax number, VAT number)"),
      issuingCountry: db
        .string({ optional: true })
        .description("ISO 3166-1 alpha-2 country code of the issuing authority"),
      validFrom: db.date({ optional: true }).description("Start date of validity period"),
      validTo: db.date({ optional: true }).description("End date of validity period"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const partnerIdentification = createPartnerIdentificationType({});
