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

export const ACCOUNTING_PERIOD_STATUSES: [string, string, string, string, string] = [
  "NEVER_OPENED",
  "FUTURE_ENTERABLE",
  "OPEN",
  "CLOSED",
  "PERMANENTLY_CLOSED",
];

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(ACCOUNTING_PERIOD_STATUSES).description("Accounting period lifecycle status"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const accountingPeriod = createAccountingPeriodType({});
