<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\ActivityLog;
use App\Models\Role;
use App\Models\User;
use App\Support\Permissions;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class RoleController extends Controller
{
    public function index()
    {
        return response()->json([
            'data' => Role::orderBy('is_system', 'desc')->orderBy('name')->get(),
            'catalogue' => Permissions::catalogue(),
        ]);
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'label' => ['required', 'string', 'max:255'],
            'name' => ['nullable', 'string'],
            'permissions' => ['nullable', 'array'],
        ]);
        $role = Role::create([
            'name' => ($data['name'] ?? null) ?: Str::slug($data['label']),
            'label' => $data['label'],
            'permissions' => $data['permissions'] ?? [],
            'is_system' => false,
        ]);
        ActivityLog::record('create', 'users', "Created role {$role->label}", $role);

        return response()->json(['data' => $role], 201);
    }

    public function update(Request $request, Role $role)
    {
        $data = $request->validate([
            'label' => ['required', 'string', 'max:255'],
            'permissions' => ['nullable', 'array'],
        ]);
        // super-admin always keeps the wildcard.
        $perms = $role->name === 'super-admin' ? ['*'] : ($data['permissions'] ?? []);
        $role->update(['label' => $data['label'], 'permissions' => $perms]);
        ActivityLog::record('update', 'users', "Updated role {$role->label}", $role);

        return response()->json(['data' => $role]);
    }

    public function destroy(Role $role)
    {
        if ($role->is_system) {
            return response()->json(['message' => 'System roles cannot be deleted.'], 422);
        }
        if (User::where('role', $role->name)->exists()) {
            return response()->json(['message' => 'This role is assigned to users.'], 422);
        }
        $role->delete();

        return response()->json(['success' => true]);
    }
}
