import {
  db,
  type TailorAnyDBField,
  type TailorAnyDBType,
  unsafeAllowAllGqlPermission,
  unsafeAllowAllTypePermission,
} from "@tailor-platform/sdk";
import { currency as currencyStub } from "../lib/_db_deps";

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

export function createCompanyType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateCompanyTypeParams<F>,
) {
  return db
    .type("Company", {
      legalName: db.string().description("Legal name of the company"),
      taxId: db.string({ optional: true }).description("Tax identification number"),
      registrationNumber: db.string({ optional: true }).description("Company registration number"),
      baseCurrencyId: db
        .uuid({ optional: true })
        .relation({
          type: "n-1",
          toward: { type: params.currencyType ?? currencyStub },
          backward: "companies",
        })
        .description("Foreign key to Currency from primitives module"),
      street: db.string({ optional: true }).description("Registered address street"),
      city: db.string({ optional: true }).description("Registered address city"),
      state: db.string({ optional: true }).description("Registered address state/province"),
      postalCode: db.string({ optional: true }).description("Registered address postal code"),
      country: db.string({ optional: true }).description("Registered address country"),
      status: db.string().description("Company lifecycle status: DRAFT, ACTIVE, INACTIVE"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const company = createCompanyType({});
