<?php

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

use App\Http\Controllers\Controller;
use App\Http\Middleware\RecordAdminApiAudit;
use App\Models\AdminSite;
use App\Lottery\ErrorCode;
use App\Services\AuditLogger;
use App\Support\AdminIntegrationSiteAccess;
use App\Support\ApiMessage;
use App\Support\ApiResponse;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

/** GET /api/v1/admin/integration-sites/{admin_site}/secrets */
final class AdminIntegrationSiteSecretsController extends Controller
{
    public function __invoke(Request $request, AdminSite $admin_site): JsonResponse
    {
        $admin = $request->lotteryAdmin();
        abort_if($admin === null, 401);

        if (! AdminIntegrationSiteAccess::canAccess($admin, $admin_site)) {
            return ApiMessage::errorResponse($request, 'admin.site_access_denied', ErrorCode::AdminForbidden->value, null, 403);
        }

        if (! $admin->isSuperAdmin() && ! $admin->hasPermissionCode('integration.site.manage')) {
            return ApiMessage::errorResponse($request, 'admin.permission_denied', ErrorCode::AdminForbidden->value, null, 403);
        }

        $sso = $admin_site->decryptedSsoJwtSecret();
        $wallet = $admin_site->decryptedWalletApiKey();

        AuditLogger::recordForAdmin(
            $admin,
            $request,
            moduleCode: 'integration',
            actionCode: 'reveal_secrets',
            targetType: 'admin_site',
            targetId: (string) $admin_site->id,
            afterJson: ['code' => $admin_site->code],
        );
        $request->attributes->set(RecordAdminApiAudit::ATTRIBUTE_AUDIT_RECORDED, true);

        return ApiResponse::success([
            'sso_jwt_secret' => is_string($sso) ? $sso : '',
            'wallet_api_key' => is_string($wallet) ? $wallet : '',
        ]);
    }
}
