import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/core";
import { salesInvoiceLifecycle } from "../db/salesInvoice.lifecycle.generated";
import type { Transaction } from "../generated/kysely-tailordb";
import { encodeJson } from "../lib/domain";
import {
  DeliveryMetadataRequiredError,
  InvalidInvoiceStatusError,
  SalesInvoiceNotFoundError,
} from "../lib/errors.generated";

export interface SendSalesInvoiceInput {
  salesInvoiceId: string;
  deliveryMetadata: Record<string, unknown>;
}

export async function run(db: Transaction, input: SendSalesInvoiceInput, ctx: CommandContext) {
  void ctx;
  const salesInvoice = await db
    .selectFrom("SalesInvoice")
    .selectAll()
    .where("id", "=", input.salesInvoiceId)
    .forUpdate()
    .executeTakeFirst();
  if (!salesInvoice) {
    return err(new SalesInvoiceNotFoundError(input.salesInvoiceId));
  }
  const nextStatus = salesInvoiceLifecycle.tryTransition(salesInvoice.status, "send");
  if (!nextStatus) {
    return err(new InvalidInvoiceStatusError(input.salesInvoiceId));
  }
  if (!Object.keys(input.deliveryMetadata ?? {}).length) {
    return err(new DeliveryMetadataRequiredError(input.salesInvoiceId));
  }
  const updated = await db
    .updateTable("SalesInvoice")
    .set({
      status: nextStatus,
      deliveryMetadata: encodeJson(input.deliveryMetadata),
    })
    .where("id", "=", input.salesInvoiceId)
    .returningAll()
    .executeTakeFirstOrThrow();
  return ok({ salesInvoice: updated });
}
