import type { DB } from "../generated/kysely-tailordb";
import { SalesOrderIdRequiredError } from "../lib/errors.generated";
import {
  buildPaginatedResult,
  DEFAULT_PAGE_SIZE,
  err,
  ok,
  type PaginationInput,
  type ReadonlyDB,
} from "@tailor-platform/erp-kit/module";

type OrderByField = "createdAt" | "invoiceDate" | "status";

export interface ListSalesInvoicesBySalesOrderInput extends PaginationInput<OrderByField> {
  salesOrderId: string;
  status?: string;
}

export async function run(db: ReadonlyDB<DB>, input: ListSalesInvoicesBySalesOrderInput) {
  if (!input.salesOrderId) {
    return err(new SalesOrderIdRequiredError("sales-invoices"));
  }
  const limit = input.limit ?? DEFAULT_PAGE_SIZE;
  const offset = input.offset ?? 0;
  const orderBy = input.orderBy ?? "invoiceDate";
  const orderDirection = input.orderDirection ?? "desc";

  let query = db
    .selectFrom("SalesInvoice")
    .selectAll()
    .where("salesOrderId", "=", input.salesOrderId);
  if (input.status) {
    query = query.where("status", "=", input.status as never);
  }

  const invoices = await query
    .orderBy(orderBy, orderDirection)
    .limit(limit + 1)
    .offset(offset)
    .execute();
  return ok(buildPaginatedResult(invoices, limit));
}
