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

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

export interface ListChannelOrdersByStatusInput extends PaginationInput<OrderByField> {
  companyId: string;
  statuses: string[];
  channelId?: string;
  dateFrom?: Date;
  dateTo?: Date;
}

export async function run(db: ReadonlyDB<DB>, input: ListChannelOrdersByStatusInput) {
  if (!input.statuses?.length) {
    return err(new StatusFilterRequiredError(input.companyId));
  }
  const limit = input.limit ?? DEFAULT_PAGE_SIZE;
  const offset = input.offset ?? 0;
  const orderBy = input.orderBy ?? "createdAt";
  const orderDirection = input.orderDirection ?? "desc";

  const rows = await db
    .selectFrom("ChannelOrder")
    .selectAll()
    .where("companyId", "=", input.companyId)
    .orderBy(orderBy, orderDirection)
    .limit(limit + 1)
    .offset(offset)
    .execute();

  const filtered = rows
    .filter((row) => input.statuses.includes(row.status))
    .filter((row) => !input.channelId || row.channelId === input.channelId)
    .filter((row) => !input.dateFrom || !row.orderDate || row.orderDate >= input.dateFrom)
    .filter((row) => !input.dateTo || !row.orderDate || row.orderDate <= input.dateTo)
    .map((row) => ({
      ...row,
      rawPayload: decodeJson<Record<string, unknown> | null>(row.rawPayload, null),
      normalizedPayload: decodeJson<Record<string, unknown> | null>(row.normalizedPayload, null),
    }));

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