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

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: "accountingPeriods",
        })
      : companyId,
    fiscalYearId: db
      .uuid()
      .relation({
        type: "n-1",
        toward: { type: fiscalYear },
        backward: "accountingPeriods",
      })
      .description("Foreign key to FiscalYear"),
    name: db.string().description("Period name"),
    startDate: db.date().description("Period start date"),
    endDate: db.date().description("Period end date"),
    periodType: db.enum(["OPERATING", "ADJUSTMENT"]).description("Period type"),
    status: db
      .enum(accountingPeriodLifecycle.states)
      .description("Accounting period lifecycle status"),
  };
};

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

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

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

export const accountingPeriod = createAccountingPeriodType({});
