<?php

namespace App\Console\Commands;

use App\Domain\Identity\Models\Person;
use App\Domain\Notification\Services\NotificationService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class SendBirthdayGreetings extends Command
{
    protected $signature = 'notifications:birthdays';
    protected $description = 'Send birthday greetings to participants with birthdays today';

    public function handle(NotificationService $notificationService): int
    {
        $today = now();

        $people = Person::whereRaw("EXTRACT(MONTH FROM date_of_birth) = ? AND EXTRACT(DAY FROM date_of_birth) = ?", [
            $today->month, $today->day,
        ])->whereHas('participants', fn ($q) => $q->where('status', 'active'))
          ->with('participants')
          ->get();

        $sent = 0;
        foreach ($people as $person) {
            $participant = $person->participants->first();
            if (!$participant) {
                continue;
            }

            $age = $person->date_of_birth?->diffInYears($today);

            try {
                $notificationService->send(
                    eventType: 'birthday_greeting',
                    recipientType: 'participant',
                    recipientId: $participant->id,
                    academyId: $participant->academy_id,
                    variables: [
                        'participant_name' => $person->name_ar ?? $person->name ?? '',
                        'age' => (string) $age,
                    ],
                    recipientEmail: $person->email,
                    recipientPhone: $person->phone,
                );
                $sent++;
            } catch (\Throwable $e) {
                Log::warning("Birthday greeting failed for person {$person->id}: " . $e->getMessage());
            }
        }

        $this->info("Sent {$sent} birthday greetings.");
        return self::SUCCESS;
    }
}
