<?php

namespace App\Http\Controllers;

use App\Services\AikDigitalApiClient;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use App\Services\Contracts\AikDigitalClientInterface;



/**
 * Exposes internal endpoints so EFU Life ops/admins can manage
 * the AIK Digital access token without touching the server directly.
 */
class AuthController extends Controller
{
    public function __construct(private AikDigitalClientInterface $apiClient) {}  // ← changed


    // ─────────────────────────────────────────────────────────────────────────

    /**
     * POST /api/aik/auth/apply-token
     *
     * Manually trigger a fresh token from AIK Digital and cache it.
     * Normally called automatically by the API client; exposed here for ops use.
     */
    public function applyToken(Request $request): JsonResponse
    {
        try {
            $token = $this->apiClient->applyToken();

            return response()->json([
                'success' => true,
                'message' => 'Access token obtained and cached successfully.',
                'token_preview' => substr($token, 0, 20) . '…', // never expose full token in response
            ]);

        } catch (\Throwable $e) {
            Log::error('AuthController@applyToken failed: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => $e->getMessage(),
            ], 500);
        }
    }

    // ─────────────────────────────────────────────────────────────────────────

    /**
     * POST /api/aik/auth/revoke-token
     *
     * Revoke the current cached token on AIK Digital.
     */
    public function revokeToken(Request $request): JsonResponse
    {
        try {
            $result = $this->apiClient->revokeToken();

            return response()->json([
                'success' => true,
                'message' => 'Token revoked. Call apply-token to get a new one.',
                'aik_response' => $result,
            ]);

        } catch (\Throwable $e) {
            Log::error('AuthController@revokeToken failed: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => $e->getMessage(),
            ], 500);
        }
    }
}
