<?php

namespace App\Domains\Admin\Actions\UpdateTenantTax;

use App\Enumerations\VatPricingMode;

class UpdateTenantTaxAction
{
    public function __construct(private UpdateTenantTaxRequest $request)
    {
    }

    public function execute(): UpdateTenantTaxResponse
    {
        $response = new UpdateTenantTaxResponse();

        if ($this->request->taxLiable) {
            $this->request->tenant->update([
                'tax_liable' => true,
                'vat_rate' => $this->clampVatRate($this->request->vatRate),
                'vat_pricing_mode' => $this->request->vatPricingMode->value,
                'tax_exemption_reason' => null,
                'tax_exemption_note' => null,
            ]);

            $response->success = true;
            $response->message = 'Steuerinformationen wurden gespeichert.';

            return $response;
        }

        $reason = $this->request->exemptionReason;

        if ($reason === null) {
            $response->message = 'Bitte einen gültigen Befreiungsgrund auswählen.';

            return $response;
        }

        $note = trim((string)$this->request->exemptionNote);

        if ($reason->requires_note && $note === '') {
            $response->message = 'Bitte einen Text für den Befreiungsgrund angeben.';

            return $response;
        }

        $this->request->tenant->update([
            'tax_liable' => false,
            'vat_rate' => 0,
            'vat_pricing_mode' => VatPricingMode::Inclusive->value,
            'tax_exemption_reason' => $reason->slug,
            'tax_exemption_note' => $reason->requires_note ? $note : null,
        ]);

        $response->success = true;
        $response->message = 'Steuerinformationen wurden gespeichert.';

        return $response;
    }

    private function clampVatRate(int $vatRate): int
    {
        return max(0, min(100, $vatRate));
    }
}
