<?php

namespace App\Console\Commands;

use App\Services\EmailProcessingService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class ProcessEmailLinks extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'emails:process-links 
                            {--limit=10 : Number of emails to process}
                            {--email-id= : Process specific email ID}
                            {--database=mysql_3 : Database connection to use}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Process emails to create links with leads based on company matching';

    /**
     * Email processing service
     *
     * @var EmailProcessingService
     */
    protected $emailService;

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct(EmailProcessingService $emailService)
    {
        parent::__construct();
        $this->emailService = $emailService;
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $database = $this->option('database');
        $limit = $this->option('limit');
        $specificEmailId = $this->option('email-id');

        $this->info("=== Email-to-Lead Link Processing Started ===");
        $this->info("Database: {$database}");

        try {
            if ($specificEmailId) {
                // Process specific email
                $email = DB::connection($database)
                    ->table('emails')
                    ->where('id', $specificEmailId)
                    ->first();

                if (!$email) {
                    $this->error("Email ID {$specificEmailId} not found");
                    return 1;
                }

                $this->processEmail($email, $database);
            } else {
                // Process unprocessed emails
                $this->processUnprocessedEmails($database, $limit);
            }

            $this->info("\n=== Processing Complete ===");
            $this->info("Check logs: storage/app/email_processing.log");
            return 0;
        } catch (\Exception $e) {
            $this->error("Error: " . $e->getMessage());
            return 1;
        }
    }

    /**
     * Process unprocessed emails
     *
     * @param string $database
     * @param int $limit
     */
    protected function processUnprocessedEmails($database, $limit)
    {
        // Get emails that haven't been processed yet
        $emails = DB::connection($database)
            ->table('emails')
            ->leftJoin('email_lead_links', 'emails.id', '=', 'email_lead_links.email_id')
            ->whereNull('email_lead_links.id')
            ->select('emails.*')
            ->limit($limit)
            ->get();

        $total = $emails->count();
        $this->info("Found {$total} unprocessed email(s)\n");

        if ($total == 0) {
            $this->info("No emails to process");
            return;
        }

        $stats = [
            'processed' => 0,
            'company_found' => 0,
            'lender_found' => 0,
            'leads_found' => 0,
            'links_created' => 0,
        ];

        $progressBar = $this->output->createProgressBar($total);
        $progressBar->start();

        foreach ($emails as $email) {
            $results = $this->emailService->processEmail($email, $database);

            $stats['processed']++;
            if ($results['company_found']) $stats['company_found']++;
            if ($results['lender_found']) $stats['lender_found']++;
            $stats['leads_found'] += $results['leads_found'];
            $stats['links_created'] += $results['links_created'];

            $progressBar->advance();
        }

        $progressBar->finish();
        $this->newLine(2);

        // Display statistics
        $this->table(
            ['Metric', 'Count'],
            [
                ['Emails Processed', $stats['processed']],
                ['Companies Found', $stats['company_found']],
                ['Lenders Found', $stats['lender_found']],
                ['Leads Found', $stats['leads_found']],
                ['Links Created', $stats['links_created']],
            ]
        );
    }

    /**
     * Process a single email
     *
     * @param object $email
     * @param string $database
     */
    protected function processEmail($email, $database)
    {
        $this->info("Processing Email ID: {$email->id}");
        $this->info("Subject: {$email->subject}");

        $results = $this->emailService->processEmail($email, $database);

        $this->line("  Company Found: " . ($results['company_found'] ? 'Yes' : 'No'));
        $this->line("  Lender Found: " . ($results['lender_found'] ? 'Yes' : 'No'));
        $this->line("  Leads Found: {$results['leads_found']}");
        $this->line("  Links Created: {$results['links_created']}");
    }
}
