import { ok, type ReadonlyDB } from "@tailor-platform/erp-kit/module";
import type { DB } from "../generated/kysely-tailordb";

export interface GetFinancialStatementInput {
  id: string;
}

/**
 * Function: getFinancialStatement
 *
 * Retrieves a single financial statement by id, along with its associated line items.
 */
export async function run(db: ReadonlyDB<DB>, input: GetFinancialStatementInput) {
  const result = await db
    .selectFrom("FinancialStatement")
    .selectAll()
    .where("id", "=", input.id)
    .executeTakeFirst();

  const lineItems = result
    ? await db
        .selectFrom("FinancialStatementLineItem")
        .selectAll()
        .where("financialStatementId", "=", input.id)
        .execute()
    : [];

  return ok({ financialStatement: result ?? null, lineItems });
}
