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

const builtins = (params: { companyType?: TailorAnyDBType }) => {
  const companyId = db.uuid().description("Foreign key to Company");
  return {
    companyId: params.companyType
      ? companyId.relation({
          type: "n-1",
          toward: { type: params.companyType },
          backward: "fiscalYears",
        })
      : companyId,
    name: db.string().description("Display name of the fiscal year"),
    startDate: db.date().description("Start date of the fiscal year"),
    endDate: db.date().description("End date of the fiscal year"),
    yearEndCloseExecuted: db
      .bool()
      .description("Tracks whether year-end close has been run for this fiscal year"),
  };
};

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

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

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

export const fiscalYear = createFiscalYearType({});
