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

type SiteOrderByField = "name" | "type" | "createdAt";

export interface ListSitesByCompanyInput extends PaginationInput<SiteOrderByField> {
  companyId: string;
  status?: string;
  type?: string;
}

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

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

  if (input.status !== undefined) {
    query = query.where("status", "=", input.status);
  }

  if (input.type !== undefined) {
    query = query.where("type", "=", input.type);
  }

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

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