<?php

namespace App\Jobs;

use App\Services\AdminNotificationService;
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;

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

    public int $tries = 3;
    public int $backoff = 10;

    public function __construct(
        protected string $type,
        protected array $data
    ) {}

    public function handle(): void
    {
        try {
            $service = new AdminNotificationService();

            match ($this->type) {
                'new_user' => $this->handleNewUser($service),
                'new_listing' => $this->handleNewListing($service),
                'new_reservation' => $this->handleNewReservation($service),
                'new_ticket' => $this->handleNewTicket($service),
                'reservation_status' => $this->handleReservationStatus($service),
                default => Log::warning("Bilinmeyen admin bildirim tipi: {$this->type}"),
            };
        } catch (\Throwable $e) {
            Log::error('SendAdminNotification hatası', [
                'type' => $this->type,
                'error' => $e->getMessage(),
            ]);
        }
    }

    protected function handleNewUser(AdminNotificationService $service): void
    {
        $user = \App\Models\User::find($this->data['user_id']);
        if ($user) {
            $service->notifyNewUser($user);
        }
    }

    protected function handleNewListing(AdminNotificationService $service): void
    {
        $listing = \App\Models\Listing::find($this->data['listing_id']);
        if ($listing) {
            $service->notifyNewListing($listing);
        }
    }

    protected function handleNewReservation(AdminNotificationService $service): void
    {
        $reservation = \App\Models\Reservation::find($this->data['reservation_id']);
        if ($reservation) {
            $service->notifyNewReservation($reservation);
        }
    }

    protected function handleNewTicket(AdminNotificationService $service): void
    {
        $ticket = \App\Models\SupportTicket::find($this->data['ticket_id']);
        if ($ticket) {
            $service->notifyNewTicket($ticket);
        }
    }

    protected function handleReservationStatus(AdminNotificationService $service): void
    {
        $reservation = \App\Models\Reservation::find($this->data['reservation_id']);
        if ($reservation) {
            $service->notifyReservationStatusChange($reservation, $this->data['old_status'] ?? 'unknown');
        }
    }
}
