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

type SCN = Selectable<"SalesCreditNote">;
type OrderByField = "createdAt" | "creditDate" | "status";

export type ListSalesCreditNotesByInvoiceInput = Pick<SCN, "salesInvoiceId"> &
  Partial<Pick<SCN, "status">> &
  PaginationInput<OrderByField>;

export async function run(db: ReadonlyDB<DB>, input: ListSalesCreditNotesByInvoiceInput) {
  if (!input.salesInvoiceId) {
    return err(new SalesInvoiceIdRequiredError("credit-notes"));
  }
  const limit = input.limit ?? DEFAULT_PAGE_SIZE;
  const offset = input.offset ?? 0;
  const orderBy = input.orderBy ?? "creditDate";
  const orderDirection = input.orderDirection ?? "desc";

  let query = db
    .selectFrom("SalesCreditNote")
    .selectAll()
    .where("salesInvoiceId", "=", input.salesInvoiceId);
  if (input.status) {
    query = query.where("status", "=", input.status);
  }

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