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

export const VARIANCE_REPORT_STATUSES = ["DRAFT", "FINAL"] as const;

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([...VARIANCE_REPORT_STATUSES])
        .description("Variance report lifecycle status"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const varianceReport = createVarianceReportType({});
