<?php

namespace Database\Seeders;

/*
 * CarPhotosSeeder — скачивает демо-фотографии с Unsplash и присваивает их автомобилям.
 * Фото подбираются по типу кузова. Удалить можно через php artisan db:seed --class=CarPhotosSeeder reset.
 */

use App\Models\Car;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;

class CarPhotosSeeder extends Seeder
{
    // Unsplash-фото по типу кузова — несколько штук для ротации
    private const PHOTOS = [
        'suv' => [
            'https://images.unsplash.com/photo-1617469767269-f80a3e3f13dc?w=900&q=80',
            'https://images.unsplash.com/photo-1555215695-3004980ad54e?w=900&q=80',
            'https://images.unsplash.com/photo-1568605117036-5fe5e7bab0b7?w=900&q=80',
            'https://images.unsplash.com/photo-1617654112329-a50e7f47e065?w=900&q=80',
            'https://images.unsplash.com/photo-1533473359331-0135ef1b58bf?w=900&q=80',
        ],
        'sedan' => [
            'https://images.unsplash.com/photo-1621007947382-bb3c3994e3fb?w=900&q=80',
            'https://images.unsplash.com/photo-1618843479313-40f8afb4b4d8?w=900&q=80',
            'https://images.unsplash.com/photo-1609752740145-6ac4be2c3947?w=900&q=80',
            'https://images.unsplash.com/photo-1492144534655-ae79c964c9d7?w=900&q=80',
        ],
        'hatchback' => [
            'https://images.unsplash.com/photo-1541899481282-d53bffe3c35d?w=900&q=80',
            'https://images.unsplash.com/photo-1606664515524-ed2f786a0bd6?w=900&q=80',
        ],
        'wagon' => [
            'https://images.unsplash.com/photo-1544636331-e26879cd4d9b?w=900&q=80',
            'https://images.unsplash.com/photo-1549317661-bd32c8ce0db2?w=900&q=80',
        ],
        'van' => [
            'https://images.unsplash.com/photo-1519641471654-76ce0107ad1b?w=900&q=80',
        ],
        'pickup' => [
            'https://images.unsplash.com/photo-1558618666-fcd25c85cd64?w=900&q=80',
        ],
        'minivan' => [
            'https://images.unsplash.com/photo-1449965408869-eaa3f722e40d?w=900&q=80',
        ],
        'default' => [
            'https://images.unsplash.com/photo-1494976388531-d1058494cdd8?w=900&q=80',
            'https://images.unsplash.com/photo-1533473359331-0135ef1b58bf?w=900&q=80',
        ],
    ];

    public function run(): void
    {
        $dir = 'cars/demo';
        Storage::disk('public')->makeDirectory($dir);

        // Скачиваем все уникальные URL один раз
        $urlToFile = $this->downloadAll($dir);

        // Счётчик ротации по каждому типу кузова
        $counters = [];

        $cars = Car::all();
        $updated = 0;

        foreach ($cars as $car) {
            $type   = $car->body_type ?? 'default';
            $pool   = self::PHOTOS[$type] ?? self::PHOTOS['default'];
            $idx    = ($counters[$type] ?? 0) % count($pool);
            $url    = $pool[$idx];
            $counters[$type] = $idx + 1;

            if (!isset($urlToFile[$url])) continue;

            $car->update(['photo_main' => $urlToFile[$url]]);
            $updated++;
        }

        $this->command->info("Фото присвоены {$updated} автомобилям.");
    }

    private function downloadAll(string $dir): array
    {
        $urlToFile = [];

        // Собираем все уникальные URL
        $allUrls = array_unique(array_merge(...array_values(self::PHOTOS)));

        foreach ($allUrls as $url) {
            $hash     = md5($url);
            $filename = $dir . '/' . $hash . '.jpg';

            // Не качаем повторно если файл уже есть
            if (Storage::disk('public')->exists($filename)) {
                $this->command->line("  [skip] {$hash}.jpg");
                $urlToFile[$url] = $filename;
                continue;
            }

            $this->command->line("  [download] {$hash}.jpg ...");

            try {
                $response = Http::timeout(30)->get($url);
                if ($response->successful()) {
                    Storage::disk('public')->put($filename, $response->body());
                    $urlToFile[$url] = $filename;
                    $this->command->line("    ✓ OK (" . round(strlen($response->body()) / 1024) . " KB)");
                } else {
                    $this->command->warn("    ✗ HTTP " . $response->status());
                }
            } catch (\Exception $e) {
                $this->command->warn("    ✗ " . $e->getMessage());
            }
        }

        return $urlToFile;
    }
}
