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

export interface GetJournalEntryInput {
  id: string;
}

/**
 * Function: getJournalEntry
 *
 * Retrieves a single journal entry by id, along with its associated journal lines.
 */
export async function run(db: ReadonlyDB<DB>, input: GetJournalEntryInput) {
  const result = await db
    .selectFrom("JournalEntry")
    .selectAll()
    .where("id", "=", input.id)
    .executeTakeFirst();

  const journalLines = result
    ? await db
        .selectFrom("JournalLine")
        .selectAll()
        .where("journalEntryId", "=", input.id)
        .execute()
    : [];

  return ok({ journalEntry: result ?? null, journalLines });
}
