import { db, type TailorAnyDBField, type TailorAnyDBType } from "@tailor-platform/sdk";
import { defaultGqlPermission, defaultPermission } from "../../../shared/modelPermissions";
import { company as companyStub } from "../lib/_db_deps";
import { accountingPeriodLifecycle } from "./accountingPeriod.lifecycle.generated";
import { fiscalYear } from "./fiscalYear";

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

export function createAccountingPeriodType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateAccountingPeriodTypeParams<F>,
) {
  return db
    .type("AccountingPeriod", {
      companyId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.companyType ?? companyStub },
          backward: "accountingPeriods",
        })
        .description("Foreign key to Company"),
      fiscalYearId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.fiscalYearType ?? 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"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const accountingPeriod = createAccountingPeriodType({});
