<?php

namespace App\Http\Controllers\Messenger;

use App\Http\Controllers\Controller;
use App\Http\Requests\Messenger\TypingRequest;
use App\Models\Messenger\Conversation;
use App\Services\Messenger\EventDispatcher;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;

class TypingController extends Controller
{
    use AuthorizesRequests;

    public function __construct(
        protected EventDispatcher $eventDispatcher
    ) {}

    public function store(TypingRequest $request): JsonResponse
    {
        try {
            $data = $request->validated();
            $userId = Auth::id();

            $conversation = Conversation::findOrFail($data['conversation_id']);
            $this->authorize('view', $conversation);

            $this->eventDispatcher->dispatchTypingStatus(
                $conversation->id,
                $userId,
                $data['is_typing']
            );

            return response()->json([
                'status' => 200,
                'message' => 'Typing status updated',
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'status' => 500,
                'message' => 'Failed to update typing status',
                'error' => $e->getMessage(),
            ], 500);
        }
    }
}
