<?php

namespace App\Services;

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

class AniSkipService
{
    // v2 kapalı, v1 çalışıyor
    const BASE       = 'https://api.aniskip.com/v1';
    const CACHE_HIT  = 60 * 60 * 24;
    const CACHE_MISS = 60 * 15; // miss → 15 dk (kısa retry)

    public function getSkipTimes(string $malId, int $episodeNumber): ?array
    {
        $key = "aniskip_v1_{$malId}_{$episodeNumber}";

        if (Cache::has($key)) {
            return Cache::get($key);
        }

        try {
            // v1: types[]=op&types[]=ed şeklinde gönderilmeli
            $url = self::BASE . "/skip-times/{$malId}/{$episodeNumber}?types[]=op&types[]=ed&episodeLength=0";
            $res = Http::timeout(6)->get($url);

            if (!$res->ok() || empty($res->json('results'))) {
                Cache::put($key, null, self::CACHE_MISS);
                return null;
            }

            $result = [];
            foreach ($res->json('results') as $item) {
                $type     = $item['skip_type'] ?? null;
                $interval = $item['interval']  ?? null;
                if (!$type || !$interval) continue;
                $result[$type] = [
                    'start' => round((float)($interval['start_time'] ?? $interval['startTime'] ?? 0), 2),
                    'end'   => round((float)($interval['end_time']   ?? $interval['endTime']   ?? 0), 2),
                ];
            }

            $data = empty($result) ? null : $result;
            Cache::put($key, $data, $data ? self::CACHE_HIT : self::CACHE_MISS);
            return $data;

        } catch (\Throwable) {
            return null;
        }
    }

    public function searchByTitle(string $title, ?string $titleEn = null, ?string $titleJp = null): ?string
    {
        $jikan = new JikanService();
        return $jikan->searchMalId($title, $titleEn, $titleJp);
    }
}
