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

type InternalOrderOrderByField = "orderNumber" | "createdAt";

export interface ListInternalOrdersInput extends PaginationInput<InternalOrderOrderByField> {
  companyId?: string;
  orderType?: string;
  status?: string;
  costCenterId?: string;
}

/**
 * Function: listInternalOrders
 *
 * Lists internal orders with optional filters for order type, status, and cost center.
 */
export async function run(db: ReadonlyDB<DB>, input: ListInternalOrdersInput) {
  if (
    input.orderType &&
    !(["OVERHEAD", "INVESTMENT", "ACCRUAL"] as const satisfies InternalOrderOrderType[]).includes(
      input.orderType as InternalOrderOrderType,
    )
  ) {
    return err(new InvalidOrderTypeFilterError(input.orderType));
  }

  if (
    input.status &&
    !(
      [
        "CREATED",
        "RELEASED",
        "TECHNICALLY_COMPLETED",
        "CLOSED",
      ] as const satisfies InternalOrderStatus[]
    ).includes(input.status as InternalOrderStatus)
  ) {
    return err(new InvalidStatusFilterError(input.status));
  }

  if (input.costCenterId) {
    const costCenter = await db
      .selectFrom("CostCenter")
      .select("id")
      .where("id", "=", input.costCenterId)
      .executeTakeFirst();

    if (!costCenter) {
      return err(new CostCenterNotFoundError(input.costCenterId));
    }
  }

  const limit = input.limit ?? DEFAULT_PAGE_SIZE;
  const offset = input.offset ?? 0;
  const orderBy = input.orderBy ?? "id";
  const orderDirection = input.orderDirection ?? "asc";

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

  if (input.companyId) {
    query = query.where("companyId", "=", input.companyId);
  }
  if (input.orderType) {
    query = query.where("orderType", "=", input.orderType as InternalOrderOrderType);
  }
  if (input.status) {
    query = query.where("status", "=", input.status as InternalOrderStatus);
  }
  if (input.costCenterId) {
    query = query.where("costCenterId", "=", input.costCenterId);
  }

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

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