<?php

namespace App\Console\Commands;

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

class RunInactivityFeeCommand extends Command
{
    protected $signature = 'fees:inactivity
                            {--preview : Preview inactivity fee impact only}
                            {--as-of= : Optional as-of date (YYYY-MM-DD)}
                            {--manual : Mark run trigger as manual}';

    protected $description = 'Run monthly inactivity maintenance fee deductions.';

    public function handle(InactivityFeeService $inactivityFeeService): int
    {
        $options = [
            'as_of_date' => $this->option('as-of') ?: null,
            'trigger' => $this->option('manual') ? 'manual' : 'auto',
        ];

        if ((bool) $this->option('preview')) {
            $preview = $inactivityFeeService->preview($options);
            $this->line('Inactivity Fee Preview');
            $this->line('----------------------');
            $this->line('As-of date: '.$preview['as_of_date']);
            $this->line('Enabled: '.(($preview['enabled'] ?? false) ? 'yes' : 'no'));
            $this->line('Inactive users due: '.(int) ($preview['inactive_users_due'] ?? 0));
            $this->line('Due months total: '.(int) ($preview['months_due_total'] ?? 0));
            $this->line('Estimated deduction: NGN '.number_format((float) ($preview['estimated_total_deduction'] ?? 0), 2));

            return self::SUCCESS;
        }

        $result = $inactivityFeeService->run($options);

        $this->line('Inactivity Fee Run');
        $this->line('------------------');
        $this->line('Status: '.(string) ($result['status'] ?? 'unknown'));
        $this->line('Run Ref: '.(string) ($result['run_reference'] ?? '-'));
        $this->line('As-of date: '.(string) ($result['as_of_date'] ?? '-'));
        $this->line('Inactive users due: '.(int) ($result['inactive_users_due'] ?? 0));
        $this->line('Due months total: '.(int) ($result['months_due_total'] ?? 0));
        $this->line('Total deducted: NGN '.number_format((float) ($result['total_deducted'] ?? 0), 2));

        if (($result['status'] ?? '') === 'failed') {
            $this->error((string) ($result['message'] ?? 'Inactivity fee run failed.'));

            return self::FAILURE;
        }

        return self::SUCCESS;
    }
}
