<?php

namespace App\Jobs;

use App\Models\Investor;
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 KycFollowUp implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        Log::info("Starting KYC follow-up check");

        // Find investors with pending KYC status for more than 7 days
        $pendingKycInvestors = Investor::where('kyc_status', 'pending')
            ->where('total_invested', '>=', 10000) // KYC required for $10K+
            ->whereDoesntHave('kycDocuments', function ($query) {
                // No documents uploaded in the last 7 days
                $query->where('created_at', '>=', now()->subDays(7));
            })
            ->get();

        $remindersSent = 0;

        foreach ($pendingKycInvestors as $investor) {
            // Check if we haven't sent a reminder in the last 7 days
            $recentReminder = $investor->investments()
                ->whereHas('emailLogs', function ($query) {
                    $query->where('email_type', 'kyc_request')
                        ->where('created_at', '>=', now()->subDays(7));
                })
                ->exists();

            if (!$recentReminder) {
                Log::info("Sending KYC follow-up to investor {$investor->id}");

                // In production, send actual reminder
                // Mail::to($investor->email)->send(new KycReminderMail($investor));

                $remindersSent++;
            }
        }

        // Also check investors with rejected documents
        $rejectedKycInvestors = Investor::where('kyc_status', 'rejected')
            ->where('total_invested', '>=', 10000)
            ->get();

        foreach ($rejectedKycInvestors as $investor) {
            Log::info("Investor {$investor->id} has rejected KYC documents - follow-up needed");
        }

        Log::info("KYC follow-up completed", [
            'pending_checked' => $pendingKycInvestors->count(),
            'reminders_sent' => $remindersSent,
            'rejected_count' => $rejectedKycInvestors->count(),
        ]);
    }
}
