<?php

namespace App\Jobs;

use App\Models\ScheduledNotificationLog;
use App\Models\User;
use App\Services\PushNotificationService;
use Carbon\Carbon;
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\Log;
use Throwable;

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

    public int $tries = 3;

    public array $backoff = [10, 30, 60];

    public int $timeout = 30;

    public function __construct(
        private readonly int $scheduledNotificationLogId
    ) {}

    public function handle(PushNotificationService $service): void
    {
        $this->send($service);
    }

    private function send(PushNotificationService $service): void
    {
        $log = ScheduledNotificationLog::find($this->scheduledNotificationLogId);

        if (!$log || $log->sent_at) {
            return;
        }

        $user = User::find($log->user_id);

        if (!$user) {
            $this->markFailed($log, 'User not found.');
            return;
        }

        [$title, $body] = $this->messageFor($log);

        try {
            $sent = $service->sendToUser($user, $title, $body, [
                'type' => 'upcoming_' . $log->reminder_type,
                'reminder_type' => $log->reminder_type,
                'notifiable_type' => $log->notifiable_type,
                'notifiable_id' => $log->notifiable_id,
                'activity_at' => $log->activity_at?->toDateTimeString(),
                'reminder_at' => $log->reminder_at?->toDateTimeString(),
            ]);

            if (!$sent) {
                $this->markFailed($log, 'Push notification service returned false.');
                return;
            }

            $log->update([
                'status' => 'sent',
                'sent_at' => now(),
                'failed_at' => null,
                'error_message' => null,
            ]);
        } catch (Throwable $e) {
            $this->markFailed($log, $e->getMessage());
            throw $e;
        }
    }

    private function messageFor(ScheduledNotificationLog $log): array
    {
        $activityAt = $log->activity_at instanceof Carbon
            ? $log->activity_at->format('d M Y, h:i A')
            : 'soon';

        return match ($log->reminder_type) {
            'follow_up' => ['Upcoming Follow-up', "You have a follow-up due at {$activityAt}."],
            'callback' => ['Upcoming Callback', "You have a callback due at {$activityAt}."],
            'meeting' => ['Upcoming Meeting', "You have a meeting at {$activityAt}."],
            'demo' => ['Upcoming Demo', "You have a demo at {$activityAt}."],
            default => ['Upcoming Activity', "You have an activity due at {$activityAt}."],
        };
    }

    private function markFailed(ScheduledNotificationLog $log, string $message): void
    {
        $log->update([
            'status' => 'failed',
            'failed_at' => now(),
            'error_message' => $message,
        ]);

        Log::warning('Upcoming activity notification failed: ' . $message, [
            'scheduled_notification_log_id' => $log->id,
            'reminder_type' => $log->reminder_type,
            'notifiable_type' => $log->notifiable_type,
            'notifiable_id' => $log->notifiable_id,
            'user_id' => $log->user_id,
        ]);
    }
}
