<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Http\Requests\Groups\StoreGroupJoinRequestRequest;
use App\Models\Group;
use App\Models\GroupJoinRequest;
use App\Services\GroupJoinRequestService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;

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

    public function store(StoreGroupJoinRequestRequest $request, Group $group): RedirectResponse|JsonResponse
    {
        $this->authorize('requestJoin', $group);

        $joinRequest = $this->joinRequests->submit($group, $request->user(), $request->validated());

        if ($request->expectsJson()) {
            return response()->json([
                'ok' => true,
                'join_request' => $this->joinRequests->mapRequest($joinRequest, $group, $request->user()),
            ]);
        }

        return back()->with('success', 'Your join request has been sent.');
    }

    public function destroy(Request $request, Group $group, GroupJoinRequest $joinRequest): RedirectResponse|JsonResponse
    {
        abort_unless((int) $joinRequest->group_id === (int) $group->id, 404);

        $updated = $this->joinRequests->withdraw($joinRequest, $request->user());

        if ($request->expectsJson()) {
            return response()->json([
                'ok' => true,
                'join_request' => $this->joinRequests->mapRequest($updated, $group, $request->user()),
            ]);
        }

        return back()->with('success', 'Your join request has been withdrawn.');
    }
}