import { authGuard, ExpressController, forbidQueryFieldGuard, tenantGuard } from "@erp/core/api";
import { ChangeStatusCustomerInvoiceByIdRequestDTO } from "@erp/customer-invoices/common";
import { ChangeStatusCustomerInvoiceUseCase } from "../../../application";
import { customerInvoicesApiErrorMapper } from "../customer-invoices-api-error-mapper";

export class ChangeStatusCustomerInvoiceController extends ExpressController {
  public constructor(private readonly useCase: ChangeStatusCustomerInvoiceUseCase) {
    super();
    this.errorMapper = customerInvoicesApiErrorMapper;

    // 🔐 Reutiliza guards de auth/tenant y prohíbe 'companyId' en query
    this.registerGuards(authGuard(), tenantGuard(), forbidQueryFieldGuard("companyId"));
  }

  async executeImpl(): Promise<any> {
    const companyId = this.getTenantId(); // garantizado por tenantGuard
    if (!companyId) {
      return this.forbiddenError("Tenant ID not found");
    }

    const { proforma_id } = this.req.params;
    if (!proforma_id) {
      return this.invalidInputError("Proforma ID missing");
    }

    const dto = this.req.body as ChangeStatusCustomerInvoiceByIdRequestDTO;
    const result = await this.useCase.execute({ proforma_id, dto, companyId });

    return result.match(
      (data) => this.ok(data),
      (err) => this.handleError(err)
    );
  }
}
