<?php

namespace App\Http\Controllers\Api\V1\Admin\User;

use App\Models\AdminUser;
use App\Support\ApiResponse;
use App\Services\AuditLogger;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use App\Support\AdminPermissionBridge;
use App\Support\AdminAccountScopeGuard;
use App\Support\AdminUserApiPresenter;
use App\Http\Requests\Admin\AdminUserPermissionSyncRequest;

/** PUT /api/v1/admin/admin-users/{admin_user}/permissions */
final class AdminUserPermissionSyncController extends Controller
{
    public function __invoke(AdminUserPermissionSyncRequest $request, AdminUser $admin_user): JsonResponse
    {
        AdminAccountScopeGuard::assertPlatformAccount($admin_user);

        $input = $request->validated();
        $slugs = AdminPermissionBridge::normalizeCanonicalLegacySlugs(array_values(array_filter(
            (array) ($input['permissions'] ?? $input['permission_slugs'] ?? []),
            static fn ($v) => is_string($v) && $v !== '',
        )));
        $siteId = AdminUser::requireDefaultAdminSiteId();

        $codes = [];
        foreach ($slugs as $slug) {
            $codes = array_merge($codes, AdminPermissionBridge::menuActionCodesForLegacy($slug));
        }
        $codes = array_values(array_unique($codes));

        $menuActionIds = DB::table('admin_menu_actions')
            ->whereIn('permission_code', $codes)
            ->where('status', 1)
            ->pluck('id')
            ->all();

        DB::transaction(function () use ($admin_user, $siteId, $menuActionIds): void {
            DB::table('admin_user_menu_actions')
                ->where('admin_user_id', $admin_user->id)
                ->where(function ($q) use ($siteId): void {
                    $q->where('site_id', $siteId)->orWhereNull('site_id');
                })
                ->delete();

            $now = now();
            foreach ($menuActionIds as $mid) {
                DB::table('admin_user_menu_actions')->insert([
                    'admin_user_id' => $admin_user->id,
                    'site_id' => $siteId,
                    'menu_action_id' => (int) $mid,
                    'granted_at' => $now,
                ]);
            }
        });

        $admin_user->load('roles');

        AuditLogger::recordForAdmin(
            $request->lotteryAdmin(),
            $request,
            'admin_users',
            'sync_permissions',
            'admin_user',
            (string) $admin_user->id,
            null,
            [
                'permission_slugs' => $slugs,
            ],
        );

        return ApiResponse::success(AdminUserApiPresenter::listItem($admin_user));
    }
}
