<?php

namespace App\Jobs;

use App\Models\Event;
use App\Models\Notification;
use App\Models\User;
use App\Services\MailerService;
use App\Services\PushService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Mail;

class SendEventReminder implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public function __construct(
        public Event $event,
        public array $reminder,
    ) {}

    public function handle(): void
    {
        $user = $this->event->user;

        if (!$user) {
            return;
        }

        \Log::info('SendEventReminder: starting', [
            'event'    => $this->event->title,
            'user'     => $user->name,
            'reminder' => $this->reminder,
        ]);

        $settings     = $user->notification_settings ?? [];
        $emailEnabled = $settings['email_enabled'] ?? false;
        $isPro        = $user->subscription?->isActive() ?? false;
        $isOwnReminder = !empty($this->event->reminders ?? []);

        $minutes = $this->reminder['minutes'] ?? 30;
        $tz      = $user->timezone ?? 'Europe/Vienna';
        $start   = $this->event->starts_at->setTimezone($tz);

        $body = match (true) {
            $minutes >= 1440 => 'Morgen um ' . $start->format('H:i') . ' Uhr',
            $minutes >= 60   => 'In ' . intval($minutes / 60) . ' Stunde(n)',
            default          => 'In ' . $minutes . ' Minuten',
        };

        // PUSH — wenn Token vorhanden (kein Pro/push_enabled Gate)
        $hasPushToken = $user->devices()
            ->where('active', true)
            ->whereNotNull('push_token')
            ->exists();

        \Log::info('SendEventReminder: user check', [
            'plan_key'     => $user->subscription?->plan?->plan_key,
            'hasPushToken' => $hasPushToken,
            'isOwnReminder'=> $isOwnReminder,
        ]);

        if ($hasPushToken) {
            PushService::send(
                $user,
                'Erinnerung: ' . $this->event->title,
                $body,
                ['type' => 'event_reminder', 'event_id' => $this->event->id]
            );

            \Log::info('Event push sent', [
                'event' => $this->event->title,
                'user'  => $user->name,
            ]);
        } else {
            \Log::warning('SendEventReminder: push skipped', ['reason' => 'no_active_token']);
        }

        // EMAIL
        if ($emailEnabled && ($isOwnReminder || $isPro)) {
            try {
                Mail::mailer(MailerService::forAutomation('event_reminder'))
                    ->to($user->email)
                    ->send(new \App\Mail\EventReminderMail($this->event, $this->reminder));
            } catch (\Throwable $e) {
                \Log::warning('EventReminder: Email failed', ['error' => $e->getMessage()]);
            }
        }

        // IN-APP — immer
        $this->sendInApp($user);
    }

    private function sendInApp(User $user): void
    {
        $tz      = $user->timezone ?? 'Europe/Vienna';
        $start   = $this->event->starts_at->setTimezone($tz);
        $minutes = $this->reminder['minutes'] ?? 30;

        $message = match (true) {
            $minutes >= 1440 => 'Morgen um ' . $start->format('H:i') . ' Uhr',
            $minutes >= 60   => 'In ' . ($minutes / 60) . ' Stunde(n)',
            default          => 'In ' . $minutes . ' Minuten',
        };

        Notification::create([
            'user_id' => $user->id,
            'type'    => 'event_reminder',
            'title'   => $this->event->title,
            'message' => $message,
            'data'    => ['event_id' => $this->event->id, 'reminder' => $this->reminder],
        ]);
    }

    public function buildMessage(): string
    {
        $tz    = $this->event->user->timezone ?? 'Europe/Vienna';
        $start = $this->event->starts_at->setTimezone($tz);

        return match ($this->reminder['type']) {
            'before' => match (true) {
                ($this->reminder['minutes'] ?? 0) >= 1440 =>
                    'Morgen: ' . $this->event->title . ' um ' . $start->format('H:i') . ' Uhr',
                ($this->reminder['minutes'] ?? 0) >= 60 =>
                    $this->event->title . ' in ' . (($this->reminder['minutes'] ?? 60) / 60) . ' Stunde(n)',
                default =>
                    $this->event->title . ' in ' . ($this->reminder['minutes'] ?? 30) . ' Minuten',
            },
            'time_of_day', 'day_before' =>
                'Heute: ' . $this->event->title . ' um ' . $start->format('H:i') . ' Uhr',
            default => $this->event->title,
        };
    }
}
