<?php

namespace App\Modules\Office365\Controllers;

use App\Http\Controllers\BaseController;
use App\Modules\Office365\Services\Office365AuthService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;

class Office365AuthController extends BaseController
{
    protected $authService;

    public function __construct(Office365AuthService $authService)
    {
        $this->authService = $authService;
    }

    /**
     * Redirect user to Office 365 for authentication
     */
    public function redirect(Request $request)
    {
        try {
            $authUrl = $this->authService->getAuthorizationUrl();
            
            if ($request->wantsJson() || $request->ajax()) {
                return response()->json([
                    'success' => true,
                    'auth_url' => $authUrl,
                    'message' => 'Redirecting to Office 365 for authentication...'
                ]);
            }
            
            return Redirect::to($authUrl);
        } catch (\Exception $e) {
            Log::error('Office365 auth redirect failed', [
                'error' => $e->getMessage(),
                'user_id' => Auth::id()
            ]);
            
            if ($request->wantsJson() || $request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Failed to initiate Office 365 authentication: ' . $e->getMessage()
                ], 500);
            }
            
            return redirect()
                ->route('admin.settings.integrations.index')
                ->with('error', 'Failed to initiate Office 365 authentication. Please try again.');
        }
    }

    /**
     * Handle Office 365 callback
     */
    public function callback(Request $request)
    {
        $code = $request->get('code');
        $error = $request->get('error');
        $errorDescription = $request->get('error_description');

        if ($error) {
            Log::warning('Office365 auth callback error', [
                'error' => $error,
                'description' => $errorDescription,
                'user_id' => Auth::id()
            ]);

            return redirect()
                ->route('admin.settings.office365.index')
                ->with('error', 'Office 365 authentication failed: ' . ($errorDescription ?: $error));
        }

        if (!$code) {
            return redirect()
                ->route('admin.settings.office365.index')
                ->with('error', 'No authorization code received from Office 365.');
        }

        try {
            $success = $this->authService->exchangeCodeForToken($code, Auth::id());
            
            if ($success) {
                return redirect()
                    ->route('admin.settings.integrations.index')
                    ->with('success', 'Office 365 calendar successfully connected!');
            } else {
                return redirect()
                    ->route('admin.settings.integrations.index')
                    ->with('error', 'Failed to complete Office 365 authentication. Please try again.');
            }
        } catch (\Exception $e) {
            Log::error('Office365 callback processing failed', [
                'error' => $e->getMessage(),
                'user_id' => Auth::id()
            ]);

            return redirect()
                ->route('admin.settings.integrations.index')
                ->with('error', 'An error occurred during authentication. Please try again.');
        }
    }

    /**
     * Revoke Office 365 access
     */
    public function revoke(Request $request)
    {
        try {
            $success = $this->authService->revokeAccess(Auth::id());
            
            if ($request->wantsJson() || $request->ajax()) {
                if ($success) {
                    return response()->json([
                        'success' => true,
                        'message' => 'Office 365 calendar access revoked successfully.'
                    ]);
                } else {
                    return response()->json([
                        'success' => false,
                        'message' => 'Failed to revoke Office 365 access.'
                    ], 500);
                }
            }

            if ($success) {
                return redirect()
                    ->route('admin.settings.integrations.index')
                    ->with('success', 'Office 365 calendar access revoked successfully.');
            } else {
                return redirect()
                    ->route('admin.settings.integrations.index')
                    ->with('error', 'Failed to revoke Office 365 access.');
            }
        } catch (\Exception $e) {
            Log::error('Office365 revoke failed', [
                'error' => $e->getMessage(),
                'user_id' => Auth::id()
            ]);

            return redirect()
                ->route('admin.settings.office365.index')
                ->with('error', 'An error occurred while revoking access.');
        }
    }

    /**
     * Test Office 365 connection (API endpoint)
     */
    public function testConnection(Request $request)
    {
        try {
            $userId = Auth::id();
            $isAuthenticated = $this->authService->isAuthenticated($userId);

            if (!$isAuthenticated) {
                return response()->json([
                    'success' => false,
                    'message' => 'Office 365 not connected. Please connect first.',
                    'auth_url' => $this->authService->getAuthorizationUrl()
                ]);
            }

            // Test the connection by attempting to get user profile
            $calendarService = app(\App\Modules\Office365\Services\Office365CalendarService::class);
            $testResult = $calendarService->testConnection($userId);

            return response()->json([
                'success' => $testResult['success'],
                'message' => $testResult['message']
            ]);

        } catch (\Exception $e) {
            Log::error('Office365 test connection failed', [
                'error' => $e->getMessage(),
                'user_id' => Auth::id()
            ]);

            return response()->json([
                'success' => false,
                'message' => 'Connection test failed: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Check authentication status (API endpoint)
     */
    public function status(Request $request)
    {
        $userId = Auth::id();
        $isAuthenticated = $this->authService->isAuthenticated($userId);

        return response()->json([
            'authenticated' => $isAuthenticated,
            'auth_url' => $isAuthenticated ? null : $this->authService->getAuthorizationUrl(),
            'user_id' => $userId
        ]);
    }
}