<?php
namespace App\Services;

use Carbon\Carbon;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class HolidayService
{
    public function isHoliday(string|Carbon $date): bool
    {
        $date = $date instanceof Carbon ? $date : Carbon::parse($date);
        if ($date->isWeekend()) {
            return true;
        }
        $holidays = $this->getHolidayDates($date->year);
        return in_array($date->toDateString(), $holidays, true);
    }

    public function getHolidayDates(int $year): array
    {
        $manual = config('holidays.dates', []);
        if (!config('holidays.auto', true)) {
            return $manual;
        }

        $country = config('holidays.country_code', 'ID');
        $cacheKey = "holidays.{$country}.{$year}";
        $ttl = config('holidays.cache_ttl', 1440);

        return Cache::remember($cacheKey, $ttl, function () use ($year, $country, $manual) {
            $provider = config('holidays.provider', 'nager');
            $dates = [];

            if ($provider === 'nager') {
                $dates = $this->fetchNagerHolidays($year, $country);
            }

            return array_values(array_unique(array_merge($manual, $dates)));
        });
    }

    private function fetchNagerHolidays(int $year, string $country): array
    {
        try {
            $url = "https://date.nager.at/api/v3/PublicHolidays/{$year}/{$country}";
            $response = Http::timeout(10)->get($url);
            if (!$response->successful()) {
                Log::warning("HolidayService: API request failed ({$response->status()}).");
                return [];
            }
            $data = $response->json();
            if (!is_array($data)) {
                return [];
            }
            return array_map(fn($item) => $item['date'] ?? null, array_filter($data, fn($item) => isset($item['date'])));
        } catch (\Exception $e) {
            Log::warning('HolidayService: '.$e->getMessage());
            return [];
        }
    }
}
