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

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));
  }
  if (salesInvoice.status !== "ISSUED") {
    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: "SENT",
      deliveryMetadata: encodeJson(input.deliveryMetadata),
      updatedAt: new Date(),
    })
    .where("id", "=", input.salesInvoiceId)
    .returningAll()
    .executeTakeFirst();
  return ok({ salesInvoice: updated! });
}
