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 { CompanyScopeRequiredError } from "../lib/errors.generated";
import { loadSalesOrderAggregate } from "../lib/repository";

type SO = Selectable<"SalesOrder">;
type OrderByField = "createdAt" | "orderDate" | "status";

export type ListSalesOrdersInput = Pick<SO, "companyId"> &
  Partial<Pick<SO, "customerId" | "status" | "channelId">> & {
    dateFrom?: Date;
    dateTo?: Date;
  } & PaginationInput<OrderByField>;

export async function run(db: ReadonlyDB<DB>, input: ListSalesOrdersInput) {
  if (!input.companyId) {
    return err(new CompanyScopeRequiredError("sales-orders"));
  }
  const limit = input.limit ?? DEFAULT_PAGE_SIZE;
  const offset = input.offset ?? 0;
  const orderBy = input.orderBy ?? "orderDate";
  const orderDirection = input.orderDirection ?? "desc";

  let query = db.selectFrom("SalesOrder").selectAll().where("companyId", "=", input.companyId);
  if (input.customerId) {
    query = query.where("customerId", "=", input.customerId);
  }
  if (input.status) {
    query = query.where("status", "=", input.status);
  }
  if (input.channelId) {
    query = query.where("channelId", "=", input.channelId);
  }

  const salesOrders = await query
    .orderBy(orderBy, orderDirection)
    .limit(limit + 1)
    .offset(offset)
    .execute();

  const filteredByDate = salesOrders.filter((row) => {
    if (input.dateFrom && row.orderDate < input.dateFrom) return false;
    if (input.dateTo && row.orderDate > input.dateTo) return false;
    return true;
  });

  const items = [];
  for (const row of filteredByDate.slice(0, limit + 1)) {
    const aggregate = await loadSalesOrderAggregate(db, row.id);
    if (!aggregate) continue;
    items.push({
      ...aggregate.salesOrder,
      fulfillmentTotals: aggregate.fulfillmentTotals,
    });
  }

  return ok(buildPaginatedResult(items, limit));
}
