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

export const BASE_CONTACT_STATUSES = ["ACTIVE", "INACTIVE"] as const;

export interface CreateContactPersonTypeParams<F extends Record<string, TailorAnyDBField>> {
  fields?: F;
  additionalStatuses?: string[];
}

export function createContactPersonType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateContactPersonTypeParams<F>,
) {
  const statuses = [...BASE_CONTACT_STATUSES, ...(params.additionalStatuses ?? [])] as [
    string,
    ...string[],
  ];

  return db
    .type("ContactPerson", {
      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(statuses).description("Contact person status: ACTIVE or INACTIVE"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const contactPerson = createContactPersonType({});
