<?php

namespace App\Http\Controllers\Chat;

use App\Http\Controllers\Controller;
use App\Http\Requests\Chat\SendMessageRequest;
use App\Models\CoachRequest;
use App\Services\ChatService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class ChatController extends Controller
{
    public function __construct(private readonly ChatService $chatService)
    {
    }

    public function show(CoachRequest $coachRequest): View
    {
        $this->authorize('chat', $coachRequest);

        $coachRequest->load(['athlete.user', 'coach.user']);

        // پیام‌های موجود را بارگذاری و پیام‌های طرف مقابل را خوانده‌شده علامت بزن
        $messages = $this->chatService->fetchNewMessages($coachRequest, auth()->user());

        return view('chat.show', compact('coachRequest', 'messages'));
    }

    public function store(SendMessageRequest $request, CoachRequest $coachRequest): RedirectResponse
    {
        $this->authorize('chat', $coachRequest);

        $this->chatService->send($coachRequest, $request->user(), $request->string('body')->toString());

        return back();
    }

    /**
     * Endpoint سبک برای AJAX Polling (هر ۱۲ ثانیه — طبق docs/architecture-addendum.md).
     */
    public function poll(Request $request, CoachRequest $coachRequest): JsonResponse
    {
        $this->authorize('chat', $coachRequest);

        $afterId = $request->integer('after_id');

        $messages = $this->chatService->fetchNewMessages($coachRequest, $request->user(), $afterId);

        return response()->json(
            $messages->map(fn ($m) => [
                'id' => $m->id,
                'body' => $m->body,
                'sender_id' => $m->sender_id,
                'sender_name' => $m->sender->fullName(),
                'is_mine' => $m->sender_id === $request->user()->id,
                'created_at' => verta($m->created_at)->format('H:i'),
            ])->values()
        );
    }
}
