<?php

namespace App\Console\Commands;

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

class CalculateSavingsInterests extends Command
{
    protected $signature = 'savings:calculate-interests';
    protected $description = 'Calculate and distribute monthly interests for all locked savings wallets';

    protected $savingsService;

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

    public function handle()
    {
        $this->info('Starting interest calculation for savings wallets...');

        try {
            $totalInterest = $this->savingsService->calculateInterests();
            
            $this->info("✓ Interest calculation completed!");
            $this->info("Total interest distributed: " . number_format($totalInterest, 2) . " XOF");

            Log::info('Savings interests calculated successfully', [
                'total_interest' => $totalInterest,
                'date' => now()
            ]);

            return 0;

        } catch (\Exception $e) {
            $this->error('Failed to calculate interests: ' . $e->getMessage());
            
            Log::error('Interest calculation failed', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);

            return 1;
        }
    }
}
