<?php

namespace App\Console\Commands;

use App\Helpers\FirstParty\ImageHash\ImageHashService;
use App\Models\MemeMedia;
use Illuminate\Console\Command;

class GenerateImageHashes extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'app:generate-image-hashes {--force : Force regeneration of existing hashes}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Generate image hashes for existing WebP URLs in MemeMedia records';

    private ImageHashService $imageHashService;

    public function __construct(ImageHashService $imageHashService)
    {
        parent::__construct();
        $this->imageHashService = $imageHashService;
    }

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $force = $this->option('force');

        $query = MemeMedia::query();

        if (! $force) {
            $query->whereNull('image_hash');
        }

        $records = $query->whereNotNull('webp_url')->get();

        if ($records->isEmpty()) {
            $this->info('No records found to process.');

            return;
        }

        $this->info("Processing {$records->count()} records...");

        $progressBar = $this->output->createProgressBar($records->count());
        $progressBar->start();

        $processed = 0;
        $failed = 0;

        foreach ($records as $record) {
            $hash = $this->imageHashService->generateHashFromUrl($record->webp_url);

            if ($hash) {
                $record->update(['image_hash' => $hash]);
                $processed++;
            } else {
                $failed++;
                $this->newLine();
                $this->error("Failed to generate hash for ID: {$record->id} - {$record->webp_url}");
            }

            $progressBar->advance();
        }

        $progressBar->finish();
        $this->newLine();

        $this->info('Processing complete!');
        $this->info("Processed: {$processed}");
        $this->info("Failed: {$failed}");
    }
}
