<?php

namespace App\Console\Commands;

use App\Models\BlogPost;
use App\Models\GalleryItem;
use App\Models\HeroSlide;
use App\Models\ProductImage;
use App\Models\Service;
use App\Models\Setting;
use App\Models\Testimonial;
use App\Support\MjsImages;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;

class SyncMjsImagesCommand extends Command
{
    protected $signature = 'images:sync-mjs {--fresh : Re-copy all photos from the mjs bike folder}';

    protected $description = 'Copy MJ\'s Bikes photos into public assets and update database image paths';

    public function handle(): int
    {
        $sourceDir = config('mjs_images.source_dir');
        $publicSubdir = config('mjs_images.public_dir');
        $destDir = public_path($publicSubdir);

        if (!File::isDirectory($sourceDir)) {
            $this->error("Source folder not found: {$sourceDir}");

            return self::FAILURE;
        }

        if (!File::isDirectory($destDir)) {
            File::makeDirectory($destDir, 0755, true);
        }

        $copied = 0;
        foreach (File::files($sourceDir) as $file) {
            $ext = strtolower($file->getExtension());
            if (!in_array($ext, ['jpg', 'jpeg', 'png', 'webp', 'gif'], true)) {
                continue;
            }

            $dest = $destDir . DIRECTORY_SEPARATOR . $file->getFilename();
            if ($this->option('fresh') || !File::exists($dest)) {
                File::copy($file->getPathname(), $dest);
                $copied++;
            }
        }

        $this->info("Copied {$copied} photo(s) to public/{$publicSubdir}/");

        $pool = MjsImages::pool();
        $poolCount = count($pool);

        HeroSlide::orderBy('sort_order')->get()->each(function (HeroSlide $slide, int $index) {
            $heroImages = config('mjs_images.hero', MjsImages::pool());
            $slide->image_path = $heroImages[$index % count($heroImages)] ?? MjsImages::path($index);
            $slide->save();
        });
        $this->info('Updated hero slides.');

        ProductImage::orderBy('id')->get()->each(function (ProductImage $image, int $index) use ($poolCount) {
            $image->image_path = MjsImages::path($index);
            $image->save();
        });
        $this->info('Updated product images.');

        Service::orderBy('id')->get()->each(function (Service $service, int $index) use ($poolCount) {
            $service->image_path = MjsImages::path($index + 3);
            $service->save();
        });
        $this->info('Updated service images.');

        BlogPost::orderBy('id')->get()->each(function (BlogPost $post, int $index) use ($poolCount) {
            $post->image_path = MjsImages::path($index + 6);
            $post->save();
        });
        $this->info('Updated blog images.');

        Testimonial::orderBy('id')->get()->each(function (Testimonial $testimonial, int $index) use ($poolCount) {
            $testimonial->image_path = MjsImages::path($index + 9);
            $testimonial->save();
        });
        $this->info('Updated testimonial images.');

        GalleryItem::orderBy('id')->get()->each(function (GalleryItem $item, int $index) use ($poolCount) {
            $item->image_path = MjsImages::path($index + 12);
            $item->save();
        });
        $this->info('Updated gallery images.');

        Setting::set('hero_image', config('mjs_images.default'));
        $this->info('Updated fallback hero setting.');

        $this->newLine();
        $this->info('All MJ\'s Bikes photos are now wired across the site.');

        return self::SUCCESS;
    }
}
