<?php

namespace Database\Factories;

use App\Importers\Image\Jobs\FinishImageModification;
use App\Models\Album;
use App\Models\Image;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\Laravel\Facades\Image as InterventionImage;
use \App\Importers\Image\Jobs\GenerateThumbnail;
use \App\Importers\Image\Jobs\GenerateFullscreen;
use Illuminate\Support\Facades\Bus;

/**
 * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Image>
 */
class ImageFactory extends Factory
{
/**
     * Configure the model factory.
     */
    public function configure(): static
    {
        return $this->afterCreating(function (Image $image) {
            $height = rand(2000, 4000);
            $width = rand(2000, 4000);
            $image_content = Http::get("https://picsum.photos/{$width}/{$height}")->body();
            $encoded = InterventionImage::read($image_content)->toAvif(config('gallery.image.quality'));
            $image_path = $image->album_id . '/original/' . $image->id . '.avif';
            Storage::disk('images')->put($image_path, $encoded);

            Bus::chain([
                Bus::batch([
                    new GenerateThumbnail($image),
                    new GenerateFullscreen($image),
                ]),
                new FinishImageModification($image),
            ])->dispatch();
        });
    }

    /**
     * Define the model's default state.
     *
     * @return array<string, mixed>
     */
    public function definition(): array
    {
        return [
            'album_id' => Album::all()->random(1)->first()->id,
            'isCover' => false,
        ];
    }
}
