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";
import { contactPersonLifecycle } from "./contactPerson.lifecycle.generated";

const builtins = {
  partnerId: db
    .uuid()
    .relation({
      type: "n-1",
      toward: { type: businessPartner },
      backward: "contactPersons",
    })
    .description("Foreign key to ORGANIZATION-type BusinessPartner"),
  firstName: db.string().description("Contact person first name"),
  lastName: db.string().description("Contact person last name"),
  email: db.string({ optional: true }).description("Contact person email address"),
  phone: db.string({ optional: true }).description("Contact person phone number"),
  jobTitle: db.string({ optional: true }).description("Contact person job title"),
  department: db.string({ optional: true }).description("Contact person department"),
  isPrimary: db.bool().description("Whether this is the primary contact for the organization"),
  status: db
    .enum(contactPersonLifecycle.states)
    .description("Contact person status: ACTIVE or INACTIVE"),
};

type ReservedFields = keyof typeof builtins | CommonReservedFields;

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

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

export const contactPerson = createContactPersonType({});
