<?php

namespace App\Http\Controllers\Api\Driver;

use App\Events\MessageSent;
use App\Http\Controllers\Controller;
use App\Models\Booking;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class ChatController extends Controller
{
    public function index(Request $request, Booking $booking): JsonResponse
    {
        $driver = $request->user()->driver;
        abort_unless($driver && $booking->driver_id === $driver->id, 404);

        $booking->messages()->where('sender_type', '!=', $request->user()::class)->update(['read_at' => now()]);

        return response()->json(['messages' => $booking->messages]);
    }

    public function store(Request $request, Booking $booking): JsonResponse
    {
        $driver = $request->user()->driver;
        abort_unless($driver && $booking->driver_id === $driver->id, 404);

        $data = $request->validate(['body' => ['required', 'string', 'max:2000']]);

        $message = $booking->messages()->create([
            'sender_type' => $request->user()::class,
            'sender_id' => $request->user()->id,
            'body' => $data['body'],
        ]);

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

        return response()->json(['message' => $message], 201);
    }
}
