<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Jobs\SendAdminNotification;
use App\Models\SupportTicket;
use App\Models\SupportTicketMessage;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class SupportTicketController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $tickets = SupportTicket::where('user_id', $request->user()->id)
            ->with('latestMessage')
            ->withCount('messages')
            ->latest()
            ->paginate(20);

        return response()->json($tickets);
    }

    public function store(Request $request): JsonResponse
    {
        $data = $request->validate([
            'subject' => 'required|string|max:255',
            'category' => 'required|in:genel,teknik,oneriler,sikayet',
            'message' => 'required|string|max:5000',
            'priority' => 'sometimes|in:low,medium,high',
        ]);

        $ticket = SupportTicket::create([
            'user_id' => $request->user()->id,
            'subject' => $data['subject'],
            'category' => $data['category'],
            'priority' => $data['priority'] ?? 'medium',
        ]);

        $ticket->messages()->create([
            'user_id' => $request->user()->id,
            'message' => $data['message'],
            'is_admin' => false,
        ]);

        $ticket->load('messages.user:id,name');

        SendAdminNotification::dispatch('new_ticket', ['ticket_id' => $ticket->id]);

        return response()->json([
            'message' => 'Destek talebi oluşturuldu',
            'ticket' => $ticket,
        ], 201);
    }

    public function show(Request $request, SupportTicket $ticket): JsonResponse
    {
        if ($ticket->user_id !== $request->user()->id) {
            return response()->json(['message' => 'Yetkisiz'], 403);
        }

        $ticket->load([
            'messages' => fn ($q) => $q->with('user:id,name,avatar')->oldest(),
        ]);

        return response()->json(['ticket' => $ticket]);
    }

    public function addMessage(Request $request, SupportTicket $ticket): JsonResponse
    {
        if ($ticket->user_id !== $request->user()->id) {
            return response()->json(['message' => 'Yetkisiz'], 403);
        }

        if ($ticket->status === 'closed') {
            return response()->json(['message' => 'Bu talep kapatılmış'], 422);
        }

        $data = $request->validate([
            'message' => 'required|string|max:5000',
        ]);

        $msg = $ticket->messages()->create([
            'user_id' => $request->user()->id,
            'message' => $data['message'],
            'is_admin' => false,
        ]);

        if ($ticket->status === 'resolved') {
            $ticket->update(['status' => 'open']);
        }

        $msg->load('user:id,name');

        return response()->json(['message' => $msg]);
    }

    public function close(Request $request, SupportTicket $ticket): JsonResponse
    {
        if ($ticket->user_id !== $request->user()->id) {
            return response()->json(['message' => 'Yetkisiz'], 403);
        }

        $ticket->update(['status' => 'closed']);

        return response()->json(['message' => 'Talep kapatıldı', 'ticket' => $ticket]);
    }
}
