<?php

namespace App\Console\Commands;

use App\Enums\ApprovalStatus;
use App\Enums\CooperationStatus;
use App\Models\Cooperation;
use App\Models\CooperationMedia;
use Illuminate\Console\Command;

class SimulateCooperationTime extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'cooperation:simulate-time {id? : The ID of the cooperation}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Simulate time passing for a specific Cooperation by moving dates to the past (Local only)';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        if (! app()->isLocal()) {
            $this->error('This command can only be run in local environment.');

            return Command::FAILURE;
        }

        $cooperationId = $this->argument('id');

        // Interactive Selection if ID not provided
        if (! $cooperationId) {
            $cooperations = Cooperation::whereIn('status', [
                CooperationStatus::PENDING,
                CooperationStatus::ASSIGNMENT,
            ])->get();

            if ($cooperations->isEmpty()) {
                $this->warn('No active cooperations (PENDING or ASSIGNMENT) found to simulate.');

                return Command::SUCCESS;
            }

            $choices = [];
            foreach ($cooperations as $c) {
                // Handle enum value safely
                $status = $c->status instanceof \UnitEnum ? $c->status->value : $c->status;
                $choices[$c->id] = "[ID: {$c->id}] {$c->title} ({$status})";
            }

            $choice = $this->choice(
                'Which cooperation do you want to fast-forward?',
                $choices
            );

            // Retrieve the ID associated with the choice
            $cooperationId = array_search($choice, $choices);
        }

        $cooperation = Cooperation::find($cooperationId);

        if (! $cooperation) {
            $this->error("Cooperation with ID {$cooperationId} not found.");

            return Command::FAILURE;
        }

        $this->info("Simulating time passage for: {$cooperation->title}");

        if ($cooperation->status === CooperationStatus::PENDING) {
            // 1. Move dates to past
            $cooperation->update([
                'initial_submission_date' => now()->subDays(8),
                'final_submission_date' => now()->subDay(),
            ]);
            $this->info('Moved dates to the past (Final Submission: Yesterday).');

            // 2. Reject unresponsive media
            $rejectedCount = CooperationMedia::where('cooperation_id', $cooperation->id)
                ->pending()
                ->update(['status' => ApprovalStatus::REJECTED]);

            if ($rejectedCount > 0) {
                $this->info("Rejected {$rejectedCount} media that didn't respond.");
            }

            // 3. Update Status
            $cooperation->update(['status' => CooperationStatus::ASSIGNMENT]);
            $this->info('Status transitioned to ASSIGNMENT.');
        } elseif ($cooperation->status === CooperationStatus::ASSIGNMENT) {
            if ($cooperation->taskAssignment) {
                // 1. Move task dates to past
                $cooperation->taskAssignment->update([
                    'start_date' => now()->subDays(8),
                    'end_date' => now()->subDay(),
                ]);
                $this->info('Moved task dates to the past (Task End: Yesterday).');

                // 2. Reject unresponsive media (assignments)
                $rejectedCount = CooperationMedia::where('cooperation_id', $cooperation->id)
                    ->pending()
                    ->update(['status' => ApprovalStatus::REJECTED]);

                if ($rejectedCount > 0) {
                    $this->info("Rejected {$rejectedCount} media that didn't respond to assignment.");
                }

                // 3. Update Status
                $cooperation->update(['status' => CooperationStatus::VERIFICATION]);
                $this->info('Status transitioned to VERIFICATION.');
            } else {
                $this->error('This ASSIGNMENT cooperation has no Task Assignment yet.');
            }
        } else {
            $status = $cooperation->status instanceof \UnitEnum ? $cooperation->status->value : $cooperation->status;
            $this->warn("Cooperation status '{$status}' is not supported for simulation. Only PENDING and ASSIGNMENT are supported.");
        }

        return Command::SUCCESS;
    }
}
