<?php

namespace App\Jobs;

use App\Models\Investment;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;

class CheckInvestmentMaturity implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        Log::info("Checking for maturing investments");

        // Find investments maturing in the next 30 days
        $maturingInvestments = Investment::where('status', 'active')
            ->where('payment_status', 'confirmed')
            ->whereNotNull('investment_term')
            ->whereNotNull('payment_completed_at')
            ->whereRaw('DATE_ADD(payment_completed_at, INTERVAL investment_term YEAR) BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 30 DAY)')
            ->get();

        foreach ($maturingInvestments as $investment) {
            $maturityDate = $investment->payment_completed_at->addYears($investment->investment_term);
            $daysUntilMaturity = now()->diffInDays($maturityDate, false);

            Log::info("Investment {$investment->reference} matures in {$daysUntilMaturity} days", [
                'investment_id' => $investment->id,
                'maturity_date' => $maturityDate->toDateString(),
            ]);

            // Send notification based on days remaining
            if ($daysUntilMaturity == 30 || $daysUntilMaturity == 14 || $daysUntilMaturity == 7 || $daysUntilMaturity == 1) {
                $this->sendMaturityNotification($investment, $daysUntilMaturity);
            }
        }

        // Find investments that have matured today
        $maturedToday = Investment::where('status', 'active')
            ->where('payment_status', 'confirmed')
            ->whereNotNull('investment_term')
            ->whereNotNull('payment_completed_at')
            ->whereRaw('DATE(DATE_ADD(payment_completed_at, INTERVAL investment_term YEAR)) = CURDATE()')
            ->get();

        foreach ($maturedToday as $investment) {
            $investment->update(['status' => 'completed']);

            Log::info("Investment {$investment->reference} has matured and marked as completed");

            // Send maturity confirmation email
            // Mail::to($investment->email)->send(new InvestmentMaturedMail($investment));
        }

        Log::info("Investment maturity check completed", [
            'maturing_soon' => $maturingInvestments->count(),
            'matured_today' => $maturedToday->count(),
        ]);
    }

    /**
     * Send maturity notification
     */
    protected function sendMaturityNotification(Investment $investment, int $daysRemaining): void
    {
        Log::info("Sending maturity notification to {$investment->email}", [
            'days_remaining' => $daysRemaining,
        ]);

        // In production, send actual email
        // Mail::to($investment->email)->send(new InvestmentMaturityNoticeMail($investment, $daysRemaining));
    }
}
