<?php

namespace App\Console\Commands;

use App\Enums\IntakeStatus;
use App\Models\Intake;
use App\Services\AuditLogger;
use Illuminate\Console\Command;

class CloseExpiredIntakes extends Command
{
    protected $signature = 'kcu:close-expired-intakes';

    protected $description = 'Close intakes whose application deadline has passed';

    public function handle(AuditLogger $audit): int
    {
        $expired = Intake::query()
            ->where('status', IntakeStatus::Open)
            ->whereNotNull('application_close_at')
            ->where('application_close_at', '<', now())
            ->get();

        foreach ($expired as $intake) {
            $intake->update(['status' => IntakeStatus::Closed]);

            $audit->log('intake.auto_closed', $intake,
                ['status' => IntakeStatus::Open->value],
                ['status' => IntakeStatus::Closed->value],
            );

            $this->info("Closed {$intake->name}.");
        }

        // Open any intake whose window has just begun.
        $due = Intake::query()
            ->where('status', IntakeStatus::Upcoming)
            ->whereNotNull('application_open_at')
            ->where('application_open_at', '<=', now())
            ->where(fn ($q) => $q->whereNull('application_close_at')->orWhere('application_close_at', '>', now()))
            ->get();

        foreach ($due as $intake) {
            $intake->update(['status' => IntakeStatus::Open]);

            $audit->log('intake.auto_opened', $intake,
                ['status' => IntakeStatus::Upcoming->value],
                ['status' => IntakeStatus::Open->value],
            );

            $this->info("Opened {$intake->name}.");
        }

        $this->info(sprintf('%d closed, %d opened.', $expired->count(), $due->count()));

        return self::SUCCESS;
    }
}
