<?php

namespace Modules\WhatsApp\Console;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Schema;
use Modules\WhatsApp\Entities\Services\WaNotifier;

/**
 * Sends the "appointment reminder" WhatsApp for appointments happening the next
 * day. Deduped per appointment, so running it more than once is safe.
 *
 * Schedule: daily (e.g. 18:00). Only runs when VetClinic is installed.
 */
class SendAppointmentReminders extends Command
{
    protected $signature = 'whatsapp:appointment-reminders {--date= : Target date Y-m-d (defaults to tomorrow)}';
    protected $description = 'Send WhatsApp reminders for next-day VetClinic appointments.';

    public function handle(WaNotifier $notifier): int
    {
        $model = \Modules\WhatsApp\Console\SendAppointmentReminders::appointmentModel();
        if (!$model || !Schema::hasTable('vc_appointments')) {
            $this->info('VetClinic not installed — nothing to do.');
            return self::SUCCESS;
        }

        $date = $this->option('date') ?: now()->addDay()->toDateString();

        $skipStatuses = ['cancelled', 'canceled', 'completed', 'done', 'no_show', 'closed'];

        $appointments = $model::whereDate('appointment_date', $date)
            ->whereNotIn('status', $skipStatuses)
            ->with(['owner', 'pet', 'doctor', 'location'])
            ->get();

        $sent = 0;
        foreach ($appointments as $appointment) {
            $notifier->appointmentReminder($appointment);
            $sent++;
        }

        $this->info("Queued reminders for {$sent} appointment(s) on {$date}.");
        return self::SUCCESS;
    }

    /** @return class-string|null */
    public static function appointmentModel(): ?string
    {
        $class = \Modules\VetClinic\Entities\VcAppointment::class;
        return class_exists($class) ? $class : null;
    }
}
