<?php

namespace App\Http\Controllers;

use App\Http\Requests\SyncUserDirectPermissionsRequest;
use App\Models\User;
use App\Support\AuditableRelations;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;
use Spatie\Permission\Models\Permission;

class UserPermissionController extends Controller
{
    public function edit(Request $request): Response
    {
        $users = User::query()
            ->select(['id', 'name', 'email'])
            ->orderBy('name', 'asc')
            ->get();

        $userId = $request->integer('user', 0) ?: $users->first()?->id;

        $user = $userId ? User::query()->find($userId) : null;

        $permissionRows = [];

        if ($user !== null) {
            $directNames = $user->getDirectPermissions()->pluck('name')->all();
            $viaRoleNames = $user->getPermissionsViaRoles()->pluck('name')->unique()->values()->all();
            $viaRoleOnlyNames = array_values(array_diff($viaRoleNames, $directNames));

            $allNames = Permission::query()
                ->where('guard_name', 'web')
                ->orderBy('name', 'asc')
                ->pluck('name')
                ->all();

            foreach ($allNames as $name) {
                if (in_array($name, $directNames, true)) {
                    $permissionRows[] = ['name' => $name, 'source' => 'direct'];
                } elseif (in_array($name, $viaRoleOnlyNames, true)) {
                    $permissionRows[] = ['name' => $name, 'source' => 'role'];
                } else {
                    $permissionRows[] = ['name' => $name, 'source' => 'none'];
                }
            }
        }

        return Inertia::render('permissions/user-permissions', [
            'users' => $users,
            'selectedUserId' => $user?->id,
            'permissionRows' => $permissionRows,
            'directPermissionNames' => $user !== null ? $user->getDirectPermissions()->pluck('name')->values()->all() : [],
        ]);
    }

    public function update(SyncUserDirectPermissionsRequest $request, User $user): RedirectResponse
    {
        AuditableRelations::syncPermissions($user, $request->validated('permissions'));

        return redirect()->route('user-permissions.edit', ['user' => $user->id])
            ->with('status', __('Direct permissions updated.'));
    }
}
