<?php

namespace App\Console\Commands;

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

class UnlockExpiredSavings extends Command
{
    protected $signature = 'savings:unlock-expired';
    protected $description = 'Automatically unlock savings wallets that have reached their expiration date';

    protected $savingsService;

    public function __construct(SavingsWalletService $savingsService)
    {
        parent::__construct();
        $this->savingsService = $savingsService;
    }

    public function handle()
    {
        $this->info('Checking for expired savings wallets...');

        try {
            $count = $this->savingsService->unlockExpiredWallets();
            
            if ($count > 0) {
                $this->info("✓ Unlocked {$count} expired savings wallet(s)");
            } else {
                $this->info('No expired wallets found');
            }

            Log::info('Expired savings unlocked successfully', [
                'count' => $count,
                'date' => now()
            ]);

            return 0;

        } catch (\Exception $e) {
            $this->error('Failed to unlock expired wallets: ' . $e->getMessage());
            
            Log::error('Expired wallet unlock failed', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);

            return 1;
        }
    }
}
