<?php

namespace App\Http\Controllers;

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

class ChatController extends Controller
{
    public function contacts()
    {
        return User::select(['id', 'first_name', 'last_name'])
            ->get()
            ->map(function ($user) {
                return [
                    'id' => $user->id,
                    'name' => $user->first_name.' '.$user->last_name,
                ];
            });
    }

    public function start(Request $request)
    {
        $user1 = auth()->id();
        $user2 = $request->user_id;

        $conversation = Conversation::whereHas('users', fn ($q) => $q->where('user_id', $user1))
            ->whereHas('users', fn ($q) => $q->where('user_id', $user2))
            ->first();

        if (! $conversation) {
            $conversation = Conversation::create();
            $conversation->users()->attach([$user1, $user2]);
        }

        return $conversation;
    }

    public function messages($id)
    {
        return Message::with('user')
            ->where('conversation_id', $id)
            ->latest()
            ->take(50)
            ->get()
            ->reverse()
            ->values();
    }

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

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

        return $message->load('user');
    }
}
