<?php

namespace App\Console\Commands;

use App\Models\Pet;
use Illuminate\Console\Command;

class FixPetAdoptionStatus extends Command
{
    protected $signature = 'pets:fix-adoption-status
                            {--dry-run : Show what would be changed without making changes}';

    protected $description = 'Fix pets that have adoption_date but status is available';

    public function handle(): int
    {
        $this->info('Fixing Pet Adoption Status');
        $this->info('==========================');
        $this->newLine();

        // Find pets with adoption_date set but status is not adopted
        $problematicPets = Pet::where('status', '!=', 'adopted')
            ->whereNotNull('adoption_date')
            ->get();

        if ($problematicPets->isEmpty()) {
            $this->info('No pets found with adoption_date but status != adopted');

            return Command::SUCCESS;
        }

        $this->info("Found {$problematicPets->count()} pets with adoption_date but status != adopted:");
        $this->newLine();

        foreach ($problematicPets as $pet) {
            $this->line("  - {$pet->name} (ID: {$pet->id}) - Status: {$pet->status} - Adoption Date: {$pet->adoption_date}");
        }

        $this->newLine();

        if ($this->option('dry-run')) {
            $this->warn('DRY RUN - No changes will be made');

            return Command::SUCCESS;
        }

        if (! $this->confirm('Do you want to update these pets to status=adopted?', true)) {
            $this->info('Cancelled');

            return Command::SUCCESS;
        }

        $updated = 0;

        foreach ($problematicPets as $pet) {
            $pet->update(['status' => 'adopted']);
            $updated++;
        }

        $this->newLine();
        $this->info("Updated {$updated} pets to status=adopted");

        return Command::SUCCESS;
    }
}
