<?php
namespace App\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class ImageDownloader
{
    /**
     * Download an external image URL and store it locally.
     * Returns the public URL of the stored image, or null on failure.
     */
    public static function store(string $url): ?string
    {
        try {
            $response = Http::withHeaders([
                'User-Agent' => 'Mozilla/5.0 (compatible; MegaBlogCrawler/2.0)',
            ])->timeout(15)->get($url);

            if (!$response->successful()) return null;

            // Validate content type
            $contentType = $response->header('Content-Type') ?? '';
            if (!str_contains($contentType, 'image/')) {
                // Try to guess from URL
                $ext = strtolower(pathinfo(parse_url($url, PHP_URL_PATH), PATHINFO_EXTENSION));
                if (!in_array($ext, ['jpg', 'jpeg', 'png', 'webp', 'gif'])) {
                    return null;
                }
            }

            // Determine extension
            if (str_contains($contentType, 'jpeg') || str_contains($contentType, 'jpg')) {
                $ext = 'jpg';
            } elseif (str_contains($contentType, 'png')) {
                $ext = 'png';
            } elseif (str_contains($contentType, 'webp')) {
                $ext = 'webp';
            } elseif (str_contains($contentType, 'gif')) {
                $ext = 'gif';
            } else {
                $ext = strtolower(pathinfo(parse_url($url, PHP_URL_PATH), PATHINFO_EXTENSION)) ?: 'jpg';
                if (!in_array($ext, ['jpg', 'jpeg', 'png', 'webp', 'gif'])) $ext = 'jpg';
            }

            // Size check (max 8MB)
            $body = $response->body();
            if (strlen($body) > 8 * 1024 * 1024) return null;

            // Save to posts/YYYY/MM/random.ext
            $path = 'posts/' . date('Y/m') . '/' . Str::random(24) . '.' . $ext;
            Storage::disk('public')->put($path, $body);

            return Storage::disk('public')->url($path);
        } catch (\Exception) {
            return null;
        }
    }
}
