<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Http\Requests\Groups\StoreGroupMemberRequest;
use App\Http\Requests\Groups\UpdateGroupMemberPermissionsRequest;
use App\Http\Requests\Groups\UpdateGroupMemberRequest;
use App\Models\Group;
use App\Models\GroupInvitation;
use App\Models\GroupMember;
use App\Models\User;
use App\Services\GroupMembershipService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;

class GroupMemberController extends Controller
{
    public function __construct(
        private readonly GroupMembershipService $memberships,
    ) {
    }

    public function store(StoreGroupMemberRequest $request, Group $group): JsonResponse
    {
        $this->authorize('manageMembers', $group);

        $invitee = User::query()
            ->whereRaw('LOWER(username) = ?', [strtolower((string) $request->validated('username'))])
            ->firstOrFail();

        $invitation = $this->memberships->inviteMember(
            $group,
            $request->user(),
            $invitee,
            (string) $request->validated('role'),
            $request->validated('note'),
            $request->integer('expires_in_days') ?: null,
        );

        return response()->json([
            'ok' => true,
            'member' => $invitation,
            'invitation' => $invitation,
            'members' => $this->memberships->mapMembers($group, $request->user()),
            'invitations' => $this->memberships->mapInvitations($group, $request->user()),
        ]);
    }

    public function update(UpdateGroupMemberRequest $request, Group $group, GroupMember $member): JsonResponse
    {
        $this->authorize('manageMembers', $group);

        abort_unless((int) $member->group_id === (int) $group->id, 404);

        $updated = $this->memberships->updateMemberRole($member, $request->user(), (string) $request->validated('role'));

        return response()->json([
            'ok' => true,
            'member' => $updated,
            'members' => $this->memberships->mapMembers($group, $request->user()),
        ]);
    }

    public function transfer(Request $request, Group $group, GroupMember $member): JsonResponse
    {
        $this->authorize('update', $group);
        abort_unless((int) $member->group_id === (int) $group->id, 404);

        $group = $this->memberships->transferOwnership($group, $member, $request->user());

        return response()->json([
            'ok' => true,
            'group_id' => (int) $group->id,
            'members' => $this->memberships->mapMembers($group, $request->user()),
        ]);
    }

    public function updatePermissions(UpdateGroupMemberPermissionsRequest $request, Group $group, GroupMember $member): JsonResponse
    {
        $this->authorize('manageMemberPermissions', $group);
        abort_unless((int) $member->group_id === (int) $group->id, 404);

        $updated = $this->memberships->updatePermissionOverrides(
            $member,
            $request->user(),
            $request->validated('permission_overrides') ?? [],
        );

        $members = $this->memberships->mapMembers($group, $request->user());

        return response()->json([
            'ok' => true,
            'member' => collect($members)->firstWhere('id', (int) $updated->id),
            'members' => $members,
        ]);
    }

    public function destroy(Request $request, Group $group, GroupMember $member): JsonResponse
    {
        $this->authorize('manageMembers', $group);
        abort_unless((int) $member->group_id === (int) $group->id, 404);

        $this->memberships->revokeMember($member, $request->user());

        return response()->json([
            'ok' => true,
            'members' => $this->memberships->mapMembers($group, $request->user()),
        ]);
    }

    public function acceptInvitation(Request $request, GroupInvitation $invitation): RedirectResponse
    {
        $member = $this->memberships->acceptInvitation($invitation, $request->user());

        return redirect()->route('studio.groups.members', ['group' => $member->group]);
    }

    public function declineInvitation(Request $request, GroupInvitation $invitation): RedirectResponse
    {
        $this->memberships->declineInvitation($invitation, $request->user());

        return redirect()->route('studio.groups.index');
    }

    public function destroyInvitation(Request $request, Group $group, GroupInvitation $invitation): JsonResponse
    {
        $this->authorize('manageMembers', $group);
        abort_unless((int) $invitation->group_id === (int) $group->id, 404);

        $this->memberships->revokeInvitation($invitation, $request->user());

        return response()->json([
            'ok' => true,
            'invitations' => $this->memberships->mapInvitations($group, $request->user()),
        ]);
    }

    public function accept(Request $request, GroupMember $member): RedirectResponse
    {
        $this->memberships->acceptLegacyInvite($member, $request->user());

        return redirect()->route('studio.groups.members', ['group' => $member->group]);
    }

    public function decline(Request $request, GroupMember $member): RedirectResponse
    {
        $this->memberships->declineLegacyInvite($member, $request->user());

        return redirect()->route('studio.groups.index');
    }
}