import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/module";
import type { Transaction } from "../generated/kysely-tailordb";
import { JournalLineNotFoundError, InvalidStatusForLineRemoveError } from "../lib/errors.generated";

export interface RemoveJournalLineInput {
  id: string;
}

export async function run(db: Transaction, input: RemoveJournalLineInput, ctx: CommandContext) {
  // 1. Fetch journal line
  const existing = await db
    .selectFrom("JournalLine")
    .selectAll()
    .where("id", "=", input.id)
    .executeTakeFirst();

  if (!existing) {
    return err(new JournalLineNotFoundError(input.id));
  }

  // 2. Validate parent entry is DRAFT
  const entry = await db
    .selectFrom("JournalEntry")
    .selectAll()
    .where("id", "=", existing.journalEntryId)
    .executeTakeFirst();

  if (entry?.status !== "DRAFT") {
    return err(new InvalidStatusForLineRemoveError(input.id));
  }

  // 3. Delete journal line
  await db.deleteFrom("JournalLine").where("id", "=", input.id).executeTakeFirstOrThrow();

  // Emit audit event recording the line removal, acting user, and timestamp
  void ctx;

  return ok({ removed: true });
}
