<?php

namespace App\Console\Commands;

use App\Enums\ConsultationStatus;
use App\Models\Consultation;
use App\Notifications\ConsultationReminder24h;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class Send24HourReminders extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'reminders:send-24h';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Send consultation reminders 24 hours before appointment';

    /**
     * Execute the console command.
     */
    public function handle(): int
    {
        $targetTime = now()->addHours(24);
        $windowStart = $targetTime->copy()->subMinutes(30);
        $windowEnd = $targetTime->copy()->addMinutes(30);

        $consultations = Consultation::query()
            ->where('status', ConsultationStatus::Approved)
            ->whereNull('reminder_24h_sent_at')
            ->whereDate('booking_date', $targetTime->toDateString())
            ->get()
            ->filter(function ($consultation) use ($windowStart, $windowEnd) {
                $consultationDateTime = Carbon::parse(
                    $consultation->booking_date->format('Y-m-d').' '.
                    $consultation->booking_time
                );

                return $consultationDateTime->between($windowStart, $windowEnd);
            });

        $count = 0;
        foreach ($consultations as $consultation) {
            try {
                $consultation->user->notify(new ConsultationReminder24h($consultation));

                $consultation->update(['reminder_24h_sent_at' => now()]);
                $count++;

                $this->info("Sent 24h reminder for consultation #{$consultation->id}");
            } catch (\Exception $e) {
                $this->error("Failed to send reminder for consultation #{$consultation->id}: {$e->getMessage()}");
                Log::error('24h reminder failed', [
                    'consultation_id' => $consultation->id,
                    'error' => $e->getMessage(),
                ]);
            }
        }

        $this->info("Sent {$count} 24-hour reminders");

        return Command::SUCCESS;
    }
}
