<?php

namespace App\Console\Commands;

use App\Enums\ApplicationStatus;
use App\Models\Application;
use App\Models\Intake;
use App\Notifications\DeadlineReminder;
use Illuminate\Console\Command;

/**
 * Nudges applicants sitting on an unsubmitted draft as the deadline nears.
 * Reminders go out at fixed distances from the close date so nobody is
 * messaged every single day.
 */
class SendDeadlineReminders extends Command
{
    protected $signature = 'kcu:send-deadline-reminders';

    protected $description = 'Remind applicants with unsubmitted drafts that the deadline is approaching';

    protected const REMIND_AT_DAYS = [14, 7, 3, 1];

    public function handle(): int
    {
        $intake = Intake::current();

        if (! $intake?->application_close_at) {
            $this->info('No open intake with a deadline. Nothing to do.');

            return self::SUCCESS;
        }

        $daysLeft = $intake->daysUntilClose();

        if (! in_array($daysLeft, self::REMIND_AT_DAYS, true)) {
            $this->info("{$daysLeft} days left; not a reminder day.");

            return self::SUCCESS;
        }

        $drafts = Application::query()
            ->where('intake_id', $intake->id)
            ->where('status', ApplicationStatus::Draft)
            ->with('applicant.user')
            ->get();

        $sent = 0;

        foreach ($drafts as $application) {
            $user = $application->applicant?->user;

            if (! $user) {
                continue;
            }

            $user->notify(new DeadlineReminder($application, $daysLeft));
            $sent++;
        }

        $this->info("Sent {$sent} reminders ({$daysLeft} days before the deadline).");

        return self::SUCCESS;
    }
}
