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

const builtins = (params: { currencyType?: TailorAnyDBType }) => {
  const baseCurrencyId = db
    .uuid({ optional: true })
    .description("Foreign key to Currency from primitives module");
  return {
    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: params.currencyType
      ? baseCurrencyId.relation({
          type: "n-1",
          toward: { type: params.currencyType },
          backward: "companies",
        })
      : baseCurrencyId,
    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.enum(companyLifecycle.states).description("Lifecycle status"),
  };
};

type ReservedFields = keyof ReturnType<typeof builtins> | CommonReservedFields;

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

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

export const company = createCompanyType({});
