<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Meet\Concerns\ScopesToAccount;
use App\Models\Room;
use App\Services\Meet\RoomService;
use App\Services\Meet\SessionService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class RoomController extends Controller
{
    use ScopesToAccount;

    public function __construct(
        protected RoomService $rooms,
        protected SessionService $sessions,
    ) {}

    public function index(Request $request): JsonResponse
    {
        $this->authorizeAbility($request, 'meetings.view');
        $organization = $this->organization($request);
        $owner = $this->ownerRef($request);

        $query = Room::owned($owner)->where('organization_id', $organization->id);
        $this->scopeToBranch($request, $query);

        $rooms = $query->orderByDesc('scheduled_at')->paginate(20);

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

    public function store(Request $request): JsonResponse
    {
        $this->authorizeAbility($request, 'meetings.create');
        $organization = $this->organization($request);

        $validated = $request->validate([
            'title' => ['required', 'string', 'max:255'],
            'description' => ['nullable', 'string'],
            'scheduled_at' => ['nullable', 'date'],
            'passcode' => ['nullable', 'string', 'max:20'],
            'settings' => ['nullable', 'array'],
            'source' => ['nullable', 'array'],
        ]);

        $room = empty($validated['scheduled_at'])
            ? $this->rooms->createInstant($request->user(), $organization, $validated)
            : $this->rooms->createScheduled($request->user(), $organization, $validated);

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

    public function show(Request $request, Room $room): JsonResponse
    {
        $this->authorizeAbility($request, 'meetings.view');
        $this->authorizeOwner($request, $room);

        return response()->json([
            'room' => $room->load('sessions'),
            'join_url' => $room->joinUrl(),
        ]);
    }

    public function start(Request $request, Room $room): JsonResponse
    {
        $this->authorizeAbility($request, 'meetings.host');
        $this->authorizeOwner($request, $room);

        $session = $this->sessions->start($room, $request->user());

        return response()->json([
            'session' => $session,
            'room_url' => route('meet.room', $session),
        ]);
    }
}
