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

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

export function createVarianceReportType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateVarianceReportTypeParams<F>,
) {
  return db
    .type("VarianceReport", {
      costObjectType: db.string().description("Polymorphic cost object type"),
      costObjectId: db.uuid().description("Polymorphic cost object identifier"),
      accountingPeriodId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.accountingPeriodType ?? accountingPeriodStub },
          backward: "varianceReports",
        })
        .description("Foreign key to AccountingPeriod"),
      companyId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.companyType ?? companyStub },
          backward: "varianceReports",
        })
        .description("Foreign key to Company"),
      totalPlanned: db.float().description("Total planned amount"),
      totalActual: db.float().description("Total actual amount"),
      totalVariance: db.float().description("Total variance amount"),
      status: db
        .enum(varianceReportLifecycle.states)
        .description("Variance report lifecycle status"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const varianceReport = createVarianceReportType({});
