<?php

namespace App\Console\Commands;

use App\Enums\FlightNotificationType;
use App\Models\UserFlight;
use App\Services\FollowerNotificationService;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;

#[Signature('app:update-arrived-flights')]
#[Description('When a flight arrives, update the arrival_processed_at timestamp and notify followers')]
class UpdateArrivedFlights extends Command
{
    public function handle(): void
    {
        $now = now()->utc();

        $userFlights = UserFlight::where('arrival_date', '<=', $now->toDateTimeString())
            ->where(function ($query) {
                $query->whereNull('arrival_processed_at')
                    ->orWhereColumn('arrival_processed_at', '<', 'arrival_date');
            })
            ->get();

        echo $userFlights->count() . " flights to update\n";
        foreach ($userFlights as $flight) {
            $flight->update(['arrival_processed_at' => $now]);
            new FollowerNotificationService()->notifyFlightEvent($flight, FlightNotificationType::Arrived);
        }
    }
}
