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

// `workCenterType` and `name` are custom fields injected by consumers via
// `createWorkCenterType({ fields })`. This query requires them, so extend
// the generated Namespace to reflect that.
type ExtendedNamespace = {
  [K in keyof Namespace]: {
    [T in keyof Namespace[K]]: T extends "WorkCenter"
      ? Namespace[K][T] & { name: string; workCenterType: string }
      : Namespace[K][T];
  };
};
type ExtendedDB = Kysely<ExtendedNamespace[keyof ExtendedNamespace]>;

type WC = Selectable<"WorkCenter"> & { name: string; workCenterType: string };
type OrderByField = "code" | "name";

export type ListWorkCentersBySiteInput = Pick<WC, "companyId"> &
  Partial<Pick<WC, "status">> & {
    siteId: string;
    workCenterType?: string;
  } & PaginationInput<OrderByField>;

/**
 * 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<ExtendedDB>, 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";
  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);
  }

  if (input.workCenterType) {
    query = query.where("workCenterType", "=", input.workCenterType);
  }

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

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