<?php

namespace App\Console\Commands;

use App\Services\TierEngine;
use Illuminate\Console\Command;

class RunTierAssessment extends Command
{
    protected $signature = 'tiers:assess
                            {--auto-approve=false : Auto-apply upgrades without admin approval (true/false)}
                            {--auto-downgrade=false : Auto-apply downgrades without admin approval (true/false)}';

    protected $description = 'Run daily tier assessment. Use --auto-approve=true and/or --auto-downgrade=true to apply changes instantly without admin approval.';

    public function handle(TierEngine $engine): int
    {
        $autoApprove    = filter_var($this->option('auto-approve'),    FILTER_VALIDATE_BOOLEAN);
        $autoDowngrade  = filter_var($this->option('auto-downgrade'),  FILTER_VALIDATE_BOOLEAN);

        if ($autoApprove || $autoDowngrade) {
            $this->info('Running tier assessment…');
            $this->info('  Auto-approve upgrades  : ' . ($autoApprove   ? 'YES' : 'NO (admin review)'));
            $this->info('  Auto-approve downgrades: ' . ($autoDowngrade  ? 'YES' : 'NO (admin review)'));

            $result = $engine->runAutoAssessment($autoApprove, $autoDowngrade);
            $this->info("✔ Auto-upgraded  : {$result['upgraded']} member(s)");
            $this->info("✔ Auto-downgraded: {$result['downgraded']} member(s)");
            $this->info("⏳ Flagged for admin review: {$result['flagged']} member(s)");
        } else {
            $this->info('Running tier assessment — all changes require admin approval…');
            $count = $engine->runQuarterlyAssessment();
            $this->info("⏳ {$count} member(s) flagged for admin review.");
        }

        return self::SUCCESS;
    }
}
