<?php

namespace App\Services;

use App\Models\TaxRate;
use Illuminate\Support\Collection;

class TaxService
{
    public function calculateTax(float $amount, string $state): float
    {
        $taxRate = TaxRate::where('state', $state)
            ->where('status', true)
            ->first();

        if (!$taxRate) {
            return 0.0;
        }

        return round(($amount * $taxRate->rate) / 100, 2);
    }

    public function getActiveTaxRates(): Collection
    {
        return TaxRate::where('status', true)
            ->orderBy('state')
            ->get();
    }

    public function getTaxRateByState(string $state): ?TaxRate
    {
        return TaxRate::where('state', $state)
            ->where('status', true)
            ->first();
    }

    public function bulkUpdateRates(array $rates): bool
    {
        try {
            foreach ($rates as $stateRate) {
                TaxRate::where('state', $stateRate['state'])
                    ->update(['rate' => $stateRate['rate']]);
            }
            return true;
        } catch (\Exception $e) {
            \Log::error('Failed to update tax rates: ' . $e->getMessage());
            return false;
        }
    }
}