<?php

declare(strict_types=1);

namespace App\Http\Controllers\Studio;

use App\Http\Controllers\Controller;
use App\Http\Requests\Groups\ReviewGroupJoinRequestRequest;
use App\Models\Group;
use App\Models\GroupJoinRequest;
use App\Services\GroupJoinRequestService;
use App\Services\GroupService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class GroupJoinRequestStudioController extends Controller
{
    public function __construct(
        private readonly GroupService $groups,
        private readonly GroupJoinRequestService $joinRequests,
    ) {
    }

    public function index(Request $request, Group $group): Response
    {
        $this->authorize('reviewJoinRequests', $group);

        return Inertia::render('Studio/StudioGroupJoinRequests', [
            'title' => $group->name . ' Join requests',
            'description' => 'Review incoming applications, compare requested roles, and approve or reject requests with audit history.',
            'studioGroup' => $this->groups->mapGroupDetail($group, $request->user()),
            'listing' => $this->joinRequests->mapRequests($group, $request->user(), $request->only(['bucket', 'page', 'per_page'])),
            'recentHistory' => $this->groups->recentHistory($group),
            'roleOptions' => [
                ['value' => Group::ROLE_MEMBER, 'label' => 'Contributor'],
                ['value' => Group::ROLE_EDITOR, 'label' => 'Editor'],
                ['value' => Group::ROLE_ADMIN, 'label' => 'Admin'],
            ],
        ]);
    }

    public function approve(ReviewGroupJoinRequestRequest $request, Group $group, GroupJoinRequest $joinRequest): RedirectResponse
    {
        $this->authorize('reviewJoinRequests', $group);
        abort_unless((int) $joinRequest->group_id === (int) $group->id, 404);

        $this->joinRequests->approve(
            $joinRequest,
            $request->user(),
            $request->validated('role'),
            $request->validated('review_notes'),
        );

        return back()->with('success', 'Join request approved.');
    }

    public function reject(ReviewGroupJoinRequestRequest $request, Group $group, GroupJoinRequest $joinRequest): RedirectResponse
    {
        $this->authorize('reviewJoinRequests', $group);
        abort_unless((int) $joinRequest->group_id === (int) $group->id, 404);

        $this->joinRequests->reject(
            $joinRequest,
            $request->user(),
            $request->validated('review_notes'),
        );

        return back()->with('success', 'Join request rejected.');
    }
}