<?php

namespace App\Console\Commands;

use App\Support\ImageHelper;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;

class BackfillThumbnails extends Command
{
    protected $signature = 'media:backfill-thumbnails {--limit=500}';
    protected $description = 'Generate thumbnails for photos missing thumbnail_path or where thumbnail equals original.';

    public function handle(): int
    {
        $limit = (int) $this->option('limit');
        $rows = DB::table('photos')
            ->select(['id','event_id','file_path','thumbnail_path'])
            ->orderBy('id')
            ->limit($limit)
            ->get();
        $count = 0;
        foreach ($rows as $r) {
            $orig = $this->relativeFromUrl((string)$r->file_path);
            $thumb = (string)($r->thumbnail_path ?? '');
            if ($thumb && $thumb !== $r->file_path) continue; // already set to different thumb
            if (! $orig) continue;
            $baseName = pathinfo($orig, PATHINFO_FILENAME);
            $destRel = "events/{$r->event_id}/photos/thumbs/{$baseName}_thumb.jpg";
            $made = ImageHelper::makeThumbnailOnDisk('public', $orig, $destRel, 640, 82);
            if ($made) {
                DB::table('photos')->where('id', $r->id)->update([
                    'thumbnail_path' => $made,
                    'updated_at' => now(),
                ]);
                $count++;
                $this->line("Photo {$r->id}: thumb created");
            }
        }
        $this->info("Done. Thumbnails generated: {$count}");
        return self::SUCCESS;
    }

    private function relativeFromUrl(string $url): ?string
    {
        // Assume Storage::url maps to /storage/*
        $p = parse_url($url, PHP_URL_PATH) ?? '';
        if (str_starts_with($p, '/storage/')) {
            return substr($p, strlen('/storage/'));
        }
        return null;
    }
}
