<?php

namespace App\Helpers\FirstParty;

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

class Tester
{
    /**
     * Test all URLs from MemeMedia model
     */
    public static function testAllMemeUrls()
    {
        $memes = MemeMedia::all();
        $results = [];
        $validCount = 0;
        $invalidCount = 0;

        foreach ($memes as $meme) {

            dump("Processing {$meme->name}...");

            $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,
            ];
        }

        $output = [
            'invalid_urls' => $invalidCount,
        ];

        dump($output);
    }
}
