<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\StoreRoleRequest;
use App\Http\Requests\UpdateRoleRequest;
use hg\apidoc\annotation as Apidoc;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Spatie\Permission\Models\Role;

#[Apidoc\Title('角色管理')]
class RoleController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:api');
        $this->middleware('permission:platform.roles.view,api')->only(['index', 'show']);
        $this->middleware('permission:platform.roles.manage,api')->only(['store', 'update', 'destroy']);
    }

    #[Apidoc\Title('角色列表'), Apidoc\Method('GET'), Apidoc\Url('/roles')]
    public function index(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'per_page' => ['nullable', 'integer', 'min:1', 'max:100'],
        ]);
        $perPage = (int) ($validated['per_page'] ?? 20);
        $roles = Role::query()->with('permissions')->latest()->paginate($perPage);

        return response()->json(['code' => 0, 'message' => 'ok', 'data' => $roles]);
    }

    #[Apidoc\Title('创建角色'), Apidoc\Method('POST'), Apidoc\Url('/roles')]
    public function store(StoreRoleRequest $request): JsonResponse
    {
        $role = Role::query()->create([
            'name' => $request->string('name')->toString(),
            'guard_name' => 'api',
        ]);

        if ($request->has('permission_ids')) {
            $role->syncPermissions($request->input('permission_ids', []));
        }

        $this->auditLog($request, 'role_create', ['metadata' => ['target_role_id' => $role->id]]);

        return response()->json(['code' => 0, 'message' => 'ok', 'data' => $role->load('permissions')], 201);
    }

    #[Apidoc\Title('角色详情'), Apidoc\Method('GET'), Apidoc\Url('/roles/{id}')]
    public function show(int $id): JsonResponse
    {
        $role = Role::query()->with('permissions')->findOrFail($id);

        return response()->json(['code' => 0, 'message' => 'ok', 'data' => $role]);
    }

    #[Apidoc\Title('更新角色'), Apidoc\Method('PUT'), Apidoc\Url('/roles/{id}')]
    public function update(UpdateRoleRequest $request, int $id): JsonResponse
    {
        $role = Role::query()->findOrFail($id);

        $role->update([
            'name' => $request->string('name', (string) $role->name)->toString(),
            'guard_name' => 'api',
        ]);

        if ($request->has('permission_ids')) {
            $role->syncPermissions($request->input('permission_ids', []));
        }

        $this->auditLog($request, 'role_update', ['metadata' => ['target_role_id' => $role->id]]);

        return response()->json(['code' => 0, 'message' => 'ok', 'data' => $role->load('permissions')]);
    }

    #[Apidoc\Title('删除角色'), Apidoc\Method('DELETE'), Apidoc\Url('/roles/{id}')]
    public function destroy(Request $request, int $id): JsonResponse
    {
        $role = Role::query()->findOrFail($id);
        $this->auditLog($request, 'role_delete', ['metadata' => ['target_role_id' => $role->id]]);
        $role->delete();

        return response()->json(['code' => 0, 'message' => 'ok', 'data' => null]);
    }
}
