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

export class ListCustomerInvoicesController extends ExpressController {
  public constructor(private readonly useCase: ListCustomerInvoicesUseCase) {
    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 { filters, pageSize, pageNumber } = this.criteria.toPrimitives();
    return Criteria.fromPrimitives(filters, "invoice_date", "DESC", pageSize, pageNumber);
  }

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

    const criteria = this.getCriteriaWithDefaultOrder();
    const result = await this.useCase.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)
    );
  }
}
