<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Services\AzureADService;
use App\Models\UserRole;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class AuthController extends Controller
{
    public function __construct(
        private AzureADService $azureADService
    ) {}

    /**
     * Redirect to Azure AD login
     */
    public function azureLogin()
    {
        $state = Str::random(40);
        session(['azure_state' => $state]);

        $authUrl = $this->azureADService->getAuthorizationUrl($state);

        return response()->json([
            'authUrl' => $authUrl,
        ]);
    }

    /**
     * Handle Azure AD callback
     */
    public function azureCallback(Request $request)
    {
        $request->validate([
            'code' => 'required|string',
            'state' => 'required|string',
        ]);

        // Verify state to prevent CSRF
        if ($request->state !== session('azure_state')) {
            return response()->json([
                'message' => 'Invalid state parameter',
            ], 400);
        }

        try {
            // Authenticate with Azure AD
            $user = $this->azureADService->authenticate($request->code);

            if (!$user) {
                return response()->json([
                    'message' => 'Authentication failed',
                ], 401);
            }

            // Generate Sanctum token
            $userRole = UserRole::where('email', $user['email'])->first();
            $token = $this->createToken($userRole);

            return response()->json([
                'user' => $user,
                'token' => $token,
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'message' => $e->getMessage(),
            ], $e->getCode() ?: 500);
        }
    }

    /**
     * Get current authenticated user
     */
    public function user(Request $request)
    {
        $email = $request->user();
        $userRole = UserRole::where('email', $email)->first();

        if (!$userRole) {
            return response()->json([
                'message' => 'User not found',
            ], 404);
        }

        return response()->json([
            'email' => $userRole->email,
            'role' => $userRole->role,
            'isActive' => $userRole->is_active,
            'lastLoginAt' => $userRole->last_login_at,
        ]);
    }

    /**
     * Logout (revoke current token)
     */
    public function logout(Request $request)
    {
        // Delete current access token
        $request->user()->currentAccessToken()->delete();

        return response()->json([
            'message' => 'Logged out successfully',
        ]);
    }

    /**
     * Create Sanctum token for user
     */
    private function createToken(UserRole $userRole): string
    {
        // Delete old tokens (optional - keep only latest)
        $userRole->tokens()->delete();

        // Create new token (expires in 30 days by default)
        $expiresAt = now()->addMinutes(config('sanctum.expiration', 43200));

        return $userRole->createToken(
            'auth-token',
            ['*'],
            $expiresAt
        )->plainTextToken;
    }
}
