import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/core";
import type { Transaction } from "../generated/kysely-tailordb";
import type { StandardAccountingEvent } from "../lib/contracts";
import { CompanyNotFoundError } from "../lib/errors.generated";
import type { OrganizationQueries } from "../module";

export type PostAccountingEventInput = StandardAccountingEvent;

export async function run(
  db: Transaction,
  input: PostAccountingEventInput,
  ctx: CommandContext,
  organizationQueries: Pick<OrganizationQueries, "getCompany">,
) {
  const { companyId, eventKind, schemaVersion, payload } = input;

  const { company } = (await organizationQueries.getCompany(db, { id: companyId }, ctx)).value;
  if (!company) return err(new CompanyNotFoundError(companyId));

  const accountingEvent = await db
    .insertInto("AccountingEvent")
    .values({
      companyId,
      eventKind,
      schemaVersion,
      occurredAt: new Date(),
      payloadJson: JSON.stringify(payload),
    })
    .returningAll()
    .executeTakeFirstOrThrow();

  return ok({ accountingEvent });
}
