<?php

namespace App\Http\Controllers\Api\App\Chat;

use App\Http\Controllers\Controller;
use App\Http\Requests\Api\App\Chat\SendMessageRequest;
use App\Http\Resources\Api\App\Chat\ChatResource;
use App\Http\Resources\Api\App\Chat\MessageResource;
use App\Models\Chat;
use App\Services\RedisMessageService;
use App\Traits\PaginateCollection;

class ChatController extends Controller
{
    use PaginateCollection;
    
    private $chat = null;

    public function __construct()
    {
        $this->chat = Chat::firstOrCreate();
    }

    public function index()
    {
        $messages = $this->chat->messages()->latest()->paginate(10);

        return response()->json([
            'status'  => 'success',
            'data'    => [
                'chat'       => ChatResource::make($this->chat),
                'messages'   => MessageResource::collection($messages->items()),
                'pagination' => $this->paginateCollection($messages),
            ],
            'message' => ''
        ]);
    }

    public function send(SendMessageRequest $request)
    {
        $message = $this->chat->messages()->create($request->validated());
        RedisMessageService::publish($message, 'chat-channel');
        return response()->json(['status' => 'success', 'data' => MessageResource::make($message), 'message' => '']);
    }
}
