<?php

declare(strict_types=1);

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Models\OperationLog;
use App\Models\Permission;
use App\Support\ApiResponse;
use hg\apidoc\annotation as Apidoc;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

#[Apidoc\Group('后台')]
#[Apidoc\Title('权限菜单')]
#[Apidoc\RouteMiddleware(['jwt.auth'])]
final class PermissionController extends Controller
{
    #[Apidoc\Title('权限菜单列表')]
    #[Apidoc\Url('/admin/permissions')]
    #[Apidoc\Method('GET')]
    #[Apidoc\RouteMiddleware(['permission:permissions'])]
    public function index(): JsonResponse
    {
        return ApiResponse::success([
            'permissions' => Permission::query()->orderBy('sort')->get(),
            'role_permissions' => DB::table('role_permissions')
                ->select(['role', 'permission_id'])
                ->get()
                ->groupBy('role')
                ->map(fn ($items) => $items->pluck('permission_id')->values())
                ->all(),
        ]);
    }

    #[Apidoc\Title('保存角色权限')]
    #[Apidoc\Url('/admin/roles/{role}/permissions')]
    #[Apidoc\Method('PUT')]
    #[Apidoc\RouteMiddleware(['permission:permissions'])]
    public function syncRole(Request $request, string $role): JsonResponse
    {
        abort_unless(in_array($role, ['teacher', 'user'], true), 422, '角色不可配置');
        $data = $request->validate(['permission_ids' => ['array'], 'permission_ids.*' => ['integer', 'exists:permissions,id']]);

        DB::table('role_permissions')->where('role', $role)->delete();
        foreach ($data['permission_ids'] ?? [] as $permissionId) {
            DB::table('role_permissions')->insert([
                'role' => $role,
                'permission_id' => $permissionId,
                'created_at' => now(),
                'updated_at' => now(),
            ]);
        }

        OperationLog::create([
            'user_id' => $request->user()->id,
            'action' => 'role.permissions_updated',
            'target_type' => 'role',
            'target_id' => null,
            'ip' => $request->ip(),
            'payload' => ['role' => $role, 'permission_ids' => $data['permission_ids'] ?? []],
        ]);

        return ApiResponse::success(null, '角色权限已更新');
    }
}
