<?php

namespace App\Services;

use App\Models\Setting;

class BunnyCdnStorage
{
    private static function creds(): ?array
    {
        $zone    = Setting::get('bunnycdn_zone', '');
        $apiKey  = Setting::get('bunnycdn_api_key', '');
        $pullUrl = rtrim(Setting::get('bunnycdn_pull_url', ''), '/');

        if (!$zone || !$apiKey || !$pullUrl) return null;

        return ['zone' => $zone, 'apiKey' => $apiKey, 'pullUrl' => $pullUrl];
    }

    /**
     * Pull URL'den dosya yolunu çıkar, CDN'den sil.
     * Altyazı ve MP4 gibi tekil dosyalar için.
     */
    public static function deleteFile(?string $url): void
    {
        if (!$url) return;
        $creds = self::creds();
        if (!$creds) return;

        if (!str_starts_with($url, $creds['pullUrl'])) return;
        $path = ltrim(substr($url, strlen($creds['pullUrl'])), '/');
        if (!$path) return;

        self::delete($creds, $path);
    }

    /**
     * Video URL'sindeki anime klasörünü (anime_XXXXX/) tamamen sil.
     * Anime silindiğinde tüm sezon/bölüm dosyaları tek seferde temizlenir.
     */
    public static function deleteAnimeFolder(?string $anyVideoUrl): void
    {
        if (!$anyVideoUrl) return;
        $creds = self::creds();
        if (!$creds) return;

        if (!str_starts_with($anyVideoUrl, $creds['pullUrl'])) return;
        $path  = ltrim(substr($anyVideoUrl, strlen($creds['pullUrl'])), '/');
        $folder = explode('/', $path)[0] ?? '';
        if (!$folder) return;

        // Trailing slash = klasör silme
        self::delete($creds, $folder . '/');
    }

    private static function delete(array $creds, string $remotePath): void
    {
        $url = "https://storage.bunnycdn.com/{$creds['zone']}/{$remotePath}";
        $ch  = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_CUSTOMREQUEST  => 'DELETE',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT        => 30,
            CURLOPT_HTTPHEADER     => ["AccessKey: {$creds['apiKey']}"],
        ]);
        curl_exec($ch);
        curl_close($ch);
    }
}
