<?php

namespace App\Http\Controllers;

use App\Models\MemeMedia;
use Illuminate\Support\Facades\Http;

class UrlValidationController extends Controller
{
    public function testAllUrls()
    {
        $memes = MemeMedia::all();
        $results = [];
        $validCount = 0;
        $invalidCount = 0;

        foreach ($memes as $meme) {
            $urls = [
                'webm_url' => $meme->webm_url,
                'mov_url' => $meme->mov_url,
                'gif_url' => $meme->gif_url,
                'webp_url' => $meme->webp_url,
            ];

            $urlResults = [];
            foreach ($urls as $type => $url) {
                try {
                    $response = Http::timeout(10)->head($url);
                    $status = $response->status();
                    $valid = $status === 200;

                    $urlResults[$type] = [
                        'url' => $url,
                        'status' => $status,
                        'valid' => $valid,
                    ];

                    $valid ? $validCount++ : $invalidCount++;
                } catch (\Exception $e) {
                    $urlResults[$type] = [
                        'url' => $url,
                        'status' => 'ERROR',
                        'valid' => false,
                        'error' => $e->getMessage(),
                    ];
                    $invalidCount++;
                }
            }

            $results[] = [
                'id' => $meme->id,
                'name' => $meme->name,
                'urls' => $urlResults,
            ];
        }

        return response()->json([
            'total_memes' => count($memes),
            'valid_urls' => $validCount,
            'invalid_urls' => $invalidCount,
            'results' => $results,
        ]);
    }
}
