<?php

namespace App\Http\Controllers;

use App\Events\ChatMessageSent;
use App\Models\Conversation;
use App\Models\Message;
use App\Models\User;
use Illuminate\Http\Request;

class ChatController extends Controller
{

    public function send(Request $request)
{
    $message = Message::create([
        'conversation_id' => $request->conversation_id,
        'user_id' => auth()->id(),
        'message' => $request->message
    ]);

    $message->load('user');

    broadcast(new ChatMessageSent($message))->toOthers();

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

    public function start(User $user)
    {
        $authUser = auth()->user();

        // buscar conversación existente
        $conversation = Conversation::whereHas('users', function ($q) use ($authUser) {
            $q->where('user_id', $authUser->id);
        })
        ->whereHas('users', function ($q) use ($user) {
            $q->where('user_id', $user->id);
        })
        ->first();

        // si no existe → crear
        if (!$conversation) {
            $conversation = Conversation::create();

            $conversation->users()->attach([
                $authUser->id,
                $user->id
            ]);
        }

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

    public function show($id)
{
    $conversation = Conversation::with([
        'messages' => function ($query) {
            $query->orderBy('created_at', 'asc');
        },
        'messages.user'
    ])->findOrFail($id);

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