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

export const VARIANCE_DIRECTIONS = ["FAVORABLE", "UNFAVORABLE"] as const;

export interface CreateVarianceReportLineTypeParams<F extends Record<string, TailorAnyDBField>> {
  fields?: F;
  varianceReportType?: TailorAnyDBType;
  costElementType?: TailorAnyDBType;
  accountingPeriodType?: TailorAnyDBType;
}

export function createVarianceReportLineType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateVarianceReportLineTypeParams<F>,
) {
  return db
    .type("VarianceReportLine", {
      varianceReportId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.varianceReportType ?? varianceReport },
          backward: "lines",
        })
        .description("Foreign key to VarianceReport"),
      costElementId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.costElementType ?? costElement },
          backward: "varianceReportLines",
        })
        .description("Foreign key to CostElement"),
      accountingPeriodId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.accountingPeriodType ?? accountingPeriodStub },
          backward: "varianceReportLines",
        })
        .description("Foreign key to AccountingPeriod"),
      plannedAmount: db.float().description("Planned/budgeted amount"),
      actualAmount: db.float().description("Actual amount"),
      varianceAmount: db.float().description("Variance amount (actual - planned)"),
      variancePercentage: db.float().description("Variance as a percentage"),
      varianceDirection: db.enum(VARIANCE_DIRECTIONS).description("Direction of the variance"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const varianceReportLine = createVarianceReportLineType({});
