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

type OrderByField = "code" | "name";

export interface ListWorkCentersBySiteInput extends PaginationInput<OrderByField> {
  companyId: string;
  siteId: string;
  status?: string;
  workCenterType?: string;
}

/**
 * Function: listWorkCentersBySite
 *
 * Lists work centers for one company and site with optional status or
 * work-center-type filters and code/name ordering.
 */
export async function run(db: ReadonlyDB<DB>, input: ListWorkCentersBySiteInput) {
  if (!input.companyId || !input.siteId) {
    return err(new SiteScopeRequiredError(input.companyId ?? input.siteId ?? "missing"));
  }

  const limit = input.limit ?? DEFAULT_PAGE_SIZE;
  const offset = input.offset ?? 0;
  const orderBy = (input.orderBy ?? "code") as "code" | "name";
  const orderDirection = input.orderDirection ?? "asc";

  let query = db
    .selectFrom("WorkCenter")
    .selectAll()
    .where("companyId", "=", input.companyId)
    .where("siteId", "=", input.siteId);

  if (input.status) {
    query = query.where("status", "=", input.status as "DRAFT" | "ACTIVE" | "INACTIVE");
  }

  if (input.workCenterType) {
    query = (query as never as { where: (...args: unknown[]) => typeof query }).where(
      "workCenterType",
      "=",
      input.workCenterType,
    );
  }

  const items = await (
    query as never as {
      orderBy: (...args: unknown[]) => {
        limit: (...args: unknown[]) => {
          offset: (...args: unknown[]) => { execute: () => Promise<unknown[]> };
        };
      };
    }
  )
    .orderBy(orderBy, orderDirection)
    .limit(limit + 1)
    .offset(offset)
    .execute();

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