<?php

namespace App\Http\Controllers;

use App\Models\MembershipApiToken;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class MembershipApiTokenController extends Controller
{
    /**
     * Display a listing of API tokens
     */
    public function index()
    {
        // Check if user is authorized
        if (auth()->user()->email !== 'naveen@example.com') {
            abort(403, 'Unauthorized access');
        }

        $tokens = MembershipApiToken::orderBy('created_at', 'desc')->paginate(10);
        $currentToken = MembershipApiToken::getCurrentToken();

        return view('admin.membership-api-tokens.index', compact('tokens', 'currentToken'));
    }

    /**
     * Generate a new API token
     */
    public function generate(Request $request)
    {
        // Check if user is authorized
        if (auth()->user()->email !== 'naveen@example.com') {
            abort(403, 'Unauthorized access');
        }

        try {
            // Request new token from API (requestNewToken handles deactivation internally)
            $token = $this->requestNewToken();

            if ($token) {
                return redirect()->route('admin.membership-api-tokens.index')
                    ->with('success', 'New API token generated successfully!');
            } else {
                return redirect()->route('admin.membership-api-tokens.index')
                    ->with('error', 'Failed to generate new API token. Please check logs.');
            }
        } catch (\Exception $e) {
            Log::error('Failed to generate API token: ' . $e->getMessage());
            return redirect()->route('admin.membership-api-tokens.index')
                ->with('error', 'Error: ' . $e->getMessage());
        }
    }

    /**
     * Refresh the current API token (generates a new one)
     */
    public function refresh(Request $request)
    {
        // Check if user is authorized
        if (auth()->user()->email !== 'naveen@example.com') {
            abort(403, 'Unauthorized access');
        }

        try {
            // The API doesn't support refresh tokens, so we generate a new one
            // This will automatically deactivate the old token
            return $this->generate($request);
        } catch (\Exception $e) {
            Log::error('Failed to refresh API token: ' . $e->getMessage());
            return redirect()->route('admin.membership-api-tokens.index')
                ->with('error', 'Error: ' . $e->getMessage());
        }
    }

    /**
     * Deactivate a specific token
     */
    public function deactivate($id)
    {
        // Check if user is authorized
        if (auth()->user()->email !== 'naveen@example.com') {
            abort(403, 'Unauthorized access');
        }

        try {
            $token = MembershipApiToken::findOrFail($id);
            $token->deactivate();

            return redirect()->route('admin.membership-api-tokens.index')
                ->with('success', 'Token deactivated successfully!');
        } catch (\Exception $e) {
            Log::error('Failed to deactivate token: ' . $e->getMessage());
            return redirect()->route('admin.membership-api-tokens.index')
                ->with('error', 'Error: ' . $e->getMessage());
        }
    }

    /**
     * Clean up expired tokens
     */
    public function cleanup()
    {
        // Check if user is authorized
        if (auth()->user()->email !== 'naveen@example.com') {
            abort(403, 'Unauthorized access');
        }

        try {
            $deletedCount = MembershipApiToken::cleanupExpiredTokens();

            return redirect()->route('admin.membership-api-tokens.index')
                ->with('success', "Cleaned up {$deletedCount} expired token(s)!");
        } catch (\Exception $e) {
            Log::error('Failed to cleanup tokens: ' . $e->getMessage());
            return redirect()->route('admin.membership-api-tokens.index')
                ->with('error', 'Error: ' . $e->getMessage());
        }
    }

    /**
     * Request a new token from the API
     */
    private function requestNewToken(): ?MembershipApiToken
    {
        try {
            $response = Http::timeout(config('membership_api.timeout', 30))
                ->withHeaders([
                    'Content-Type' => 'application/json',
                    'x-api-key' => config('membership_api.key')
                ])
                ->post(config('membership_api.base_url') . '/v1/login/', [
                    'username' => 'LJIWebApi@thelalit.com',
                    'password' => 'LJIWeb#2@3@34Nj2'
                ]);

            // Log API response
            Log::info('Membership API Token Response', [
                'status' => $response->status(),
                'response' => $response->json()
            ]);

            if ($response->successful()) {
                $tokenData = $response->json();

                // Deactivate old tokens
                MembershipApiToken::where('is_active', true)->update(['is_active' => false]);

                // Store new token
                $tokenRecord = MembershipApiToken::createFromResponse($tokenData);

                return $tokenRecord;
            }

            Log::error('Failed to get API token', [
                'status' => $response->status(),
                'response' => $response->json()
            ]);

            return null;
        } catch (\Exception $e) {
            Log::error('API Token Request Error: ' . $e->getMessage());
            throw $e;
        }
    }
}
