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

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

export function createFiscalYearType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateFiscalYearTypeParams<F>,
) {
  return db
    .type("FiscalYear", {
      companyId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.companyType ?? companyStub },
          backward: "fiscalYears",
        })
        .description("Foreign key to Company"),
      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"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const fiscalYear = createFiscalYearType({});
