import { ExpressController, authGuard, forbidQueryFieldGuard, tenantGuard } from "@erp/core/api";
import { Criteria } from "@repo/rdx-criteria/server";
import { ListCustomersUseCase } from "../../../application";

export class ListCustomersController extends ExpressController {
  public constructor(private readonly listCustomers: ListCustomersUseCase) {
    super();
    // 🔐 Reutiliza guards de auth/tenant y prohíbe 'companyId' en query
    this.useGuards(authGuard(), tenantGuard(), forbidQueryFieldGuard("companyId"));
  }

  private getCriteriaWithDefaultOrder() {
    if (this.criteria.hasOrder()) {
      return this.criteria;
    }

    const { q: quicksearch, filters, pageSize, pageNumber } = this.criteria.toPrimitives();
    return Criteria.fromPrimitives(filters, "name", "ASC", pageSize, pageNumber, quicksearch);
  }

  protected async executeImpl() {
    const companyId = this.getTenantId();
    if (!companyId) {
      return this.forbiddenError("Tenant ID not found");
    }

    const criteria = this.getCriteriaWithDefaultOrder();
    const result = await this.listCustomers.execute({ criteria, companyId });

    return result.match(
      (data) =>
        this.ok(data, {
          "X-Total-Count": String(data.total_items),
          "Pagination-Count": String(data.total_pages),
          "Pagination-Page": String(data.page),
          "Pagination-Limit": String(data.per_page),
        }),
      (err) => this.handleError(err)
    );
  }
}
