<?php

namespace App\Console\Commands;

use App\Models\ApplicationFollowUpReminder;
use App\Models\EmailDeliveryLog;
use App\Services\Email\TransactionalEmailSender;
use App\Services\Settings\SettingsService;
use Illuminate\Console\Command;
use Throwable;

class SendApplicationFollowUpReminders extends Command
{
    protected $signature = 'applications:send-follow-up-reminders {--dry-run : Show due reminders without sending email}';

    protected $description = 'Send email reminders for due application follow-ups.';

    public function handle(SettingsService $settings, TransactionalEmailSender $emailSender): int
    {
        if (! $settings->isEnabled('notifications.application_reminder_email_enabled')) {
            $this->warn('Application reminder emails are disabled in settings.');

            return self::SUCCESS;
        }

        $sent = 0;
        $failed = 0;

        ApplicationFollowUpReminder::query()
            ->with(['user', 'application.importedJob'])
            ->where('status', ApplicationFollowUpReminder::STATUS_PENDING)
            ->whereDate('due_on', '<=', now()->toDateString())
            ->orderBy('due_on')
            ->chunkById(100, function ($reminders) use ($emailSender, &$sent, &$failed): void {
                foreach ($reminders as $reminder) {
                    $application = $reminder->application;
                    $user = $reminder->user;
                    $job = $application?->importedJob;

                    if (! $application || ! $user || ! $job) {
                        $reminder->update([
                            'status' => ApplicationFollowUpReminder::STATUS_FAILED,
                            'failure_reason' => 'Missing application, user, or job record.',
                        ]);
                        $failed++;

                        continue;
                    }

                    if ($this->option('dry-run')) {
                        $this->line("Would remind {$user->email} about {$job->title}.");

                        continue;
                    }

                    try {
                        $subject = 'Follow up on '.$job->title;
                        $html = view('emails.applications.follow-up-reminder', [
                            'subject' => $subject,
                            'preheader' => 'A job application follow-up is due today.',
                            'application' => $application,
                            'job' => $job,
                        ])->render();

                        $emailSender->send(
                            toEmail: $user->email,
                            toName: $user->name,
                            subject: $subject,
                            html: $html,
                            text: "Your follow-up for {$job->title} is due. Open your pipeline: ".route('applications.pipeline'),
                            userId: $user->id,
                            type: EmailDeliveryLog::TYPE_APPLICATION_FOLLOW_UP,
                            metadata: [
                                'application_id' => $application->id,
                                'reminder_id' => $reminder->id,
                                'imported_job_id' => $job->id,
                            ],
                            resendable: true,
                        );

                        $reminder->update([
                            'status' => ApplicationFollowUpReminder::STATUS_SENT,
                            'sent_at' => now(),
                            'failure_reason' => null,
                        ]);

                        $sent++;
                    } catch (Throwable $exception) {
                        report($exception);

                        $reminder->update([
                            'status' => ApplicationFollowUpReminder::STATUS_FAILED,
                            'failure_reason' => $exception->getMessage(),
                        ]);

                        $failed++;
                    }
                }
            });

        $this->info("Application follow-up reminders complete. Sent: {$sent}. Failed: {$failed}.");

        return $failed > 0 ? self::FAILURE : self::SUCCESS;
    }
}
