<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Chat;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;
use App\Services\ExpoPushService;

class ChatController extends Controller
{
    public function index(Request $request, $receiverId): JsonResponse
    {
        $userId = Auth::id();

        $messages = Chat::where(function ($q) use ($userId, $receiverId) {
            $q->where('user_id', $userId)
                ->where('receiver_id', $receiverId);
        })
            ->orWhere(function ($q) use ($userId, $receiverId) {
                $q->where('user_id', $receiverId)
                    ->where('receiver_id', $userId);
            })
            ->orderBy('created_at', 'asc')
            ->get();

        // Отмечаем как прочитанные
        Chat::where('receiver_id', $userId)
            ->where('user_id', $receiverId)
            ->update(['is_read' => true]);

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

    public function show($receiverId)
    {
        $user = auth()->user();

        $messages = Chat::where(function ($q) use ($user, $receiverId) {
            $q->where('user_id', $user->id)->where('receiver_id', $receiverId);
        })->orWhere(function ($q) use ($user, $receiverId) {
            $q->where('user_id', $receiverId)->where('receiver_id', $user->id);
        })
            ->with(['user', 'receiver'])
            ->orderBy('created_at')
            ->get();

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

    // 📨 Отправить сообщение
    public function store(Request $request, ExpoPushService $expoPushService): JsonResponse
    {
        $validated = $request->validate([
            'receiver_id' => 'required|exists:users,id',
            'message' => 'required|string|max:2000',
        ]);

        $sender = Auth::user();

        if ($sender->id === (int) $validated['receiver_id']) {
            return response()->json(['error' => 'Нельзя отправить сообщение самому себе'], 400);
        }

        $chat = Chat::create([
            'user_id' => Auth::id(),
            'receiver_id' => $validated['receiver_id'],
            'message' => $validated['message'],
            'is_system' => false,
            'is_read' => false,
        ]);

        $receiver = User::find($validated['receiver_id']);

        // 📲 PUSH уведомление
        if ($receiver && $receiver->expo_push_token) {
            $expoPushService->send(
                $receiver->expo_push_token,
                'Новое сообщение',
                $sender->name . ': ' . $validated['message'],
                [
                    'type' => 'chat_message',
                    'chatUserId' => $sender->id,
                ]
            );
        }

        return response()->json($chat->load(['user', 'receiver']), 201);
    }

    public function dialogs(): JsonResponse
    {
        $userId = Auth::id();

        $dialogs = Chat::where('user_id', $userId)
            ->orWhere('receiver_id', $userId)
            ->with(['user', 'receiver'])
            ->orderBy('updated_at', 'desc')
            ->get()
            ->groupBy(function ($chat) use ($userId) {
                return $chat->user_id === $userId ? $chat->receiver_id : $chat->user_id;
            })
            ->map(function ($messages) {
                $last = $messages->last();
                return [
                    'last_message' => $last->message,
                    'is_read' => $last->is_read,
                    'user' => $last->user,
                    'receiver' => $last->receiver,
                    'updated_at' => $last->updated_at,
                ];
            })
            ->values();

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