<?php

namespace App\Console\Commands;

use App\Services\MembershipRenewalService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class ProcessAutoRenewalsCommand extends Command
{
    /**
     * The name and signature of the console command.
     */
    protected $signature = 'membership:process-auto-renewals';

    /**
     * The console command description.
     */
    protected $description = 'Process automatic membership renewals for eligible members';

    public function __construct(
        protected MembershipRenewalService $renewalService
    ) {
        parent::__construct();
    }

    /**
     * Execute the console command.
     */
    public function handle(): int
    {
        $this->info('Starting automatic membership renewal processing...');

        $members = $this->renewalService->getMembersEligibleForAutoRenewal();

        if ($members->isEmpty()) {
            $this->info('No members eligible for automatic renewal.');
            Log::info('ProcessAutoRenewals: no eligible members found.');
            return self::SUCCESS;
        }

        $this->info("Found {$members->count()} member(s) eligible for renewal.");

        $processed = 0;
        $failed    = 0;

        foreach ($members as $member) {
            try {
                $this->renewalService->processRenewal($member, 'automatic', null);

                $processed++;
                $this->line("  ✓ Renewed: {$member->full_name} ({$member->membership_code})");

                Log::info('ProcessAutoRenewals: renewal processed', [
                    'member_id'       => $member->id,
                    'membership_code' => $member->membership_code,
                ]);
            } catch (\Throwable $e) {
                $failed++;
                $this->error("  ✗ Failed:  {$member->full_name} ({$member->membership_code}) — {$e->getMessage()}");

                Log::error('ProcessAutoRenewals: renewal failed', [
                    'member_id'       => $member->id,
                    'membership_code' => $member->membership_code,
                    'error'           => $e->getMessage(),
                    'trace'           => $e->getTraceAsString(),
                ]);
            }
        }

        $this->newLine();
        $this->info("Renewal processing complete.");
        $this->table(
            ['Result', 'Count'],
            [
                ['Processed successfully', $processed],
                ['Failed',                $failed],
                ['Total eligible',        $members->count()],
            ]
        );

        Log::info('ProcessAutoRenewals: completed', [
            'processed' => $processed,
            'failed'    => $failed,
            'total'     => $members->count(),
        ]);

        return $failed > 0 ? self::FAILURE : self::SUCCESS;
    }
}
