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

type OrderByField = "createdAt";

export interface ListStockMovementsInput extends PaginationInput<OrderByField> {
  status?: string;
  movementType?: string;
  warehouseId?: string;
  dateFrom?: Date;
  dateTo?: Date;
}

export async function run(db: ReadonlyDB<DB>, input: ListStockMovementsInput) {
  const limit = input.limit ?? DEFAULT_PAGE_SIZE;
  const offset = input.offset ?? 0;
  const orderBy = input.orderBy ?? "createdAt";
  const orderDirection = input.orderDirection ?? "desc";

  let query = db.selectFrom("StockMovement").selectAll();

  if (input.status) {
    query = query.where(
      "status",
      "=",
      input.status as "DRAFT" | "CONFIRMED" | "DONE" | "CANCELLED",
    );
  }
  if (input.movementType) {
    query = query.where(
      "movementType",
      "=",
      input.movementType as
        | "GOODS_RECEIPT"
        | "GOODS_ISSUE"
        | "INTERNAL_TRANSFER"
        | "BLOCK"
        | "UNBLOCK",
    );
  }
  if (input.warehouseId) {
    const locationIds = await db
      .selectFrom("StorageLocation")
      .select("id")
      .where("warehouseId", "=", input.warehouseId)
      .execute();

    if (locationIds.length === 0) {
      return ok(buildPaginatedResult([], limit));
    }

    const moveLineMovementIds = await db
      .selectFrom("StockMoveLine")
      .select("stockMovementId")
      .where(
        "sourceLocationId",
        "in",
        locationIds.map((l) => l.id),
      )
      .execute();

    const destMoveLineMovementIds = await db
      .selectFrom("StockMoveLine")
      .select("stockMovementId")
      .where(
        "destinationLocationId",
        "in",
        locationIds.map((l) => l.id),
      )
      .execute();

    const uniqueMovementIds = [
      ...new Set([
        ...moveLineMovementIds.map((m) => m.stockMovementId),
        ...destMoveLineMovementIds.map((m) => m.stockMovementId),
      ]),
    ];

    if (uniqueMovementIds.length === 0) {
      return ok(buildPaginatedResult([], limit));
    }

    query = query.where("id", "in", uniqueMovementIds);
  }
  if (input.dateFrom) {
    query = query.where("createdAt", ">=", input.dateFrom);
  }
  if (input.dateTo) {
    query = query.where("createdAt", "<=", input.dateTo);
  }

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

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