import {
  db,
  type TailorAnyDBField,
  type TailorAnyDBType,
  unsafeAllowAllGqlPermission,
  unsafeAllowAllTypePermission,
} from "@tailor-platform/sdk";
import { account as accountStub, accountGroup as accountGroupStub } from "../lib/_db_deps";
import { financialStatement } from "./financialStatement";

export const FINANCIAL_STATEMENT_LINE_ITEM_LINE_TYPES: [string, string, string] = [
  "DETAIL",
  "SUBTOTAL",
  "TOTAL",
];

export interface CreateFinancialStatementLineItemTypeParams<
  F extends Record<string, TailorAnyDBField>,
> {
  fields?: F;
  financialStatementType?: TailorAnyDBType;
  accountType?: TailorAnyDBType;
  accountGroupType?: TailorAnyDBType;
}

export function createFinancialStatementLineItemType<
  const F extends Record<string, TailorAnyDBField>,
>(params: CreateFinancialStatementLineItemTypeParams<F>) {
  return db
    .type("FinancialStatementLineItem", {
      financialStatementId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.financialStatementType ?? financialStatement },
          backward: "lineItems",
        })
        .description("Foreign key to FinancialStatement"),
      accountId: db
        .uuid({ optional: true })
        .relation({
          type: "n-1",
          toward: { type: params.accountType ?? accountStub },
          backward: "financialStatementLineItems",
        })
        .description("Foreign key to Account for DETAIL line items (coa-management)"),
      accountGroupId: db
        .uuid({ optional: true })
        .relation({
          type: "n-1",
          toward: { type: params.accountGroupType ?? accountGroupStub },
          backward: "financialStatementLineItems",
        })
        .description("Foreign key to AccountGroup (coa-management)"),
      label: db.string().description("Display label for the line item"),
      amount: db.float().description("Current period amount in base currency"),
      comparativeAmount: db
        .float({ optional: true })
        .description("Comparative period amount, present when comparative data was requested"),
      lineType: db
        .enum(FINANCIAL_STATEMENT_LINE_ITEM_LINE_TYPES)
        .description("Line type: DETAIL, SUBTOTAL, or TOTAL"),
      sectionType: db
        .string()
        .description(
          "Report section where this line item appears (e.g., Current Assets, Revenue, Operating Expenses)",
        ),
      sortOrder: db.int().description("Display positioning order within the statement"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const financialStatementLineItem = createFinancialStatementLineItemType({});
