import {
  type CommonReservedFields,
  type NoReservedFields,
  defaultGqlPermission,
  defaultPermission,
} from "@tailor-platform/erp-kit/core";
import { db, type TailorAnyDBField } from "@tailor-platform/sdk";
import { businessPartner } from "./businessPartner";

export const ADDRESS_TYPES = ["BILLING", "SHIPPING", "REGISTERED", "OTHER"] as const;

const builtins = {
  partnerId: db
    .uuid()
    .relation({
      type: "n-1",
      toward: { type: businessPartner },
      backward: "partnerAddresses",
    })
    .description("Foreign key to BusinessPartner"),
  addressType: db
    .enum(["BILLING", "SHIPPING", "REGISTERED", "OTHER"])
    .description("Address purpose: BILLING, SHIPPING, REGISTERED, OTHER"),
  line1: db.string().description("Address line 1"),
  line2: db.string({ optional: true }).description("Address line 2"),
  city: db.string().description("City"),
  state: db.string({ optional: true }).description("State or province"),
  postalCode: db.string().description("Postal code"),
  country: db.string().description("ISO 3166-1 alpha-2 country code"),
  isDefault: db.bool().description("Whether this is the default address for its type"),
};

type ReservedFields = keyof typeof builtins | CommonReservedFields;

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

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

export const partnerAddress = createPartnerAddressType({});
