<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ValidationException;

class AuthController extends Controller
{
    /**
     * Handle an incoming authentication request.
     *
     * @throws ValidationException
     */
    public function login(Request $request): JsonResponse
    {
        $request->validate([
            'email' => ['required', 'string', 'email'],
            'password' => ['required', 'string'],
        ]);

        if (!Auth::attempt($request->only('email', 'password'))) {
            throw ValidationException::withMessages([
                'email' => __('The provided credentials are incorrect.'),
            ]);
        }

        $user = $request->user();

        // Check if email is verified
        if (!$user->hasVerifiedEmail()) {
            Auth::guard('web')->logout();
            return response()->json([
                'message' => 'Email not verified. Please verify your email address.',
                'error' => 'EMAIL_NOT_VERIFIED'
            ], 403);
        }

        // Update last login time
        $user->update([
            'derniere_connexion_at' => now(),
        ]);

        // Check if account is suspended
        if ($user->statut->value === 'suspendu') {
            Auth::guard('web')->logout();
            return response()->json([
                'message' => 'Account is suspended',
                'error' => 'ACCOUNT_SUSPENDED'
            ], 403);
        }

        $token = $user->createToken('auth-token')->plainTextToken;

        return response()->json([
            'message' => 'Login successful',
            'user' => $user,
            'token' => $token
        ]);
    }

    /**
     * Destroy an authenticated session.
     */
    public function logout(Request $request): JsonResponse
    {
        $token = $request->user()->currentAccessToken();
        if ($token && !($token instanceof \Laravel\Sanctum\TransientToken)) {
            $token->delete();
        }

        return response()->json([
            'message' => 'Logout successful'
        ]);
    }

    /**
     * Get the authenticated user.
     */
    public function me(Request $request): JsonResponse
    {
        $user = $request->user();

        // Load role-specific relations
        if ($user->isClient()) {
            $user->load('client.ville', 'client.quartier');
        } elseif ($user->isCandidat()) {
            $user->load('candidat.ville', 'candidat.quartierDomicile', 'candidat.parrain');
        }

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

    /**
     * Check if user profile is complete.
     */
    public function profileComplete(Request $request): JsonResponse
    {
        $user = $request->user();

        return response()->json([
            'is_complete' => $user->isProfileComplete()
        ]);
    }
}
