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

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(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const varianceReportLine = createVarianceReportLineType({});
