<?php

declare(strict_types=1);

namespace App\Console\Commands;

use App\Models\Artwork;
use App\Services\ArtworkOriginalFileLocator;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;

final class InspectArtworkOriginalCommand extends Command
{
    protected $signature = 'artworks:inspect-original
        {--artwork-id= : Artwork ID to inspect}
        {--id= : Legacy alias for artwork ID}';

    protected $description = 'Show which original artwork file path resolves for an artwork and print the output URLs.';

    public function handle(ArtworkOriginalFileLocator $locator): int
    {
        $artworkId = $this->resolveArtworkIdOption();
        if ($artworkId === null) {
            $this->error('Provide --artwork-id=ID.');

            return self::FAILURE;
        }

        $artwork = Artwork::query()
            ->withTrashed()
            ->select(['id', 'slug', 'file_name', 'file_path', 'hash', 'file_ext'])
            ->find($artworkId);

        if (! $artwork) {
            $this->error(sprintf('Artwork %d not found.', $artworkId));

            return self::FAILURE;
        }

        $localPath = $locator->resolveLocalPath($artwork);
        $objectPath = $locator->resolveObjectPath($artwork);
        $objectUrl = $locator->resolveObjectUrl($artwork);
        $downloadUrl = route('art.download', ['id' => (int) $artwork->id]);
        $artworkUrl = route('art.show', [
            'id' => (int) $artwork->id,
            'slug' => (string) ($artwork->slug ?? ''),
        ]);

        $this->line('artwork_id: ' . (string) $artwork->id);
        $this->line('file_name: ' . (string) ($artwork->file_name ?? ''));
        $this->line('file_ext: ' . (string) ($artwork->file_ext ?? ''));
        $this->line('stored_file_path: ' . (string) ($artwork->file_path ?? ''));
        $this->line('source_file: ' . ($localPath !== '' ? $localPath : '(unresolved local path)'));
        $this->line('source_file_exists: ' . (File::isFile($localPath) ? 'yes' : 'no'));
        $this->line('source_object: ' . ($objectPath !== '' ? $objectPath : '(unresolved object path)'));
        $this->line('output_url: ' . ($objectUrl !== null && $objectUrl !== '' ? $objectUrl : '(unresolved object url)'));
        $this->line('download_url: ' . $downloadUrl);
        $this->line('artwork_url: ' . $artworkUrl);

        return self::SUCCESS;
    }

    private function resolveArtworkIdOption(): ?int
    {
        $artworkId = $this->option('artwork-id');
        if ($artworkId !== null) {
            return max(1, (int) $artworkId);
        }

        $legacyId = $this->option('id');
        if ($legacyId !== null) {
            return max(1, (int) $legacyId);
        }

        return null;
    }
}