<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Validation\ValidationException;

class AuthController extends Controller
{
    public function login(Request $request): JsonResponse
    {
        $credentials = $request->validate([
            'email' => ['required', 'email'],
            'password' => ['required', 'string'],
        ]);

        $key = $this->throttleKey($request);
        if (RateLimiter::tooManyAttempts($key, 5)) {
            $seconds = RateLimiter::availableIn($key);
            Log::warning('sso.login.lockout', [
                'email' => strtolower($credentials['email']),
                'ip' => $request->ip(),
                'ua' => substr((string) $request->userAgent(), 0, 200),
                'retry_after' => $seconds,
            ]);
            throw ValidationException::withMessages([
                'email' => ["Too many attempts. Try again in {$seconds} seconds."],
            ])->status(429);
        }

        /** @var User|null $user */
        $user = User::where('email', $credentials['email'])->first();
        if (!$user || !Hash::check($credentials['password'], $user->password)) {
            RateLimiter::hit($key, 300);
            $this->logEvent(null, 'login.failed', $request, ['email' => strtolower($credentials['email'])]);
            throw ValidationException::withMessages([
                'email' => ['The provided credentials are incorrect.'],
            ]);
        }
        RateLimiter::clear($key);

        // Optional: record last login
        $user->forceFill(['email_verified_at' => $user->email_verified_at])->saveQuietly();

        $expiryMinutes = (int) config('sanctum.expiration', 60);
        $expiresAt = now()->addMinutes($expiryMinutes);
        $token = $user->createToken(
            name: 'sso-app',
            abilities: ['*'],
            expiresAt: $expiresAt
        )->plainTextToken;
        $claims = $user->buildClaims();

        $this->logEvent($user->id, 'login.success', $request, ['expires_at' => $expiresAt]);

        return response()->json([
            'access_token' => $token,
            'token_type' => 'Bearer',
            'user' => [
                'id' => $user->id,
                'name' => $user->name,
                'email' => $user->email,
            ],
            'claims' => $claims,
        ]);
    }

    public function userinfo(Request $request): JsonResponse
    {
        /** @var User $user */
        $user = $request->user();
        $claims = $user->buildClaims();

        return response()->json([
            'sub' => $user->id,
            'email' => $user->email,
            'name' => $user->name,
            ...$claims,
        ]);
    }

    public function logout(Request $request): JsonResponse
    {
        /** @var User $user */
        $user = $request->user();
        if ($request->user()?->currentAccessToken()) {
            $request->user()->currentAccessToken()->delete();
        } else {
            // Revoke all tokens if current token is missing (fallback)
            $user?->tokens()?->delete();
        }

        Auth::guard('web')->logout();

        $this->logEvent($user?->id, 'logout', $request);

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

    public function refresh(Request $request): JsonResponse
    {
        /** @var User $user */
        $user = $request->user();
        $current = $request->user()?->currentAccessToken();
        if ($current) {
            $current->delete();
        }

        $expiryMinutes = (int) config('sanctum.expiration', 60);
        $expiresAt = now()->addMinutes($expiryMinutes);
        $newToken = $user->createToken(
            name: 'sso-app',
            abilities: ['*'],
            expiresAt: $expiresAt
        )->plainTextToken;
        $claims = $user->buildClaims();

        $this->logEvent($user->id, 'token.refresh', $request, ['expires_at' => $expiresAt]);

        return response()->json([
            'access_token' => $newToken,
            'token_type' => 'Bearer',
            'claims' => $claims,
            'expires_at' => $expiresAt,
        ]);
    }

    private function throttleKey(Request $request): string
    {
        return 'login:'.strtolower((string) $request->input('email')).'|'.$request->ip();
    }

    private function logEvent(?int $userId, string $type, Request $request, array $meta = []): void
    {
        \App\Models\AuthEvent::create([
            'user_id' => $userId,
            'type' => $type,
            'ip' => $request->ip(),
            'ua' => substr((string) $request->userAgent(), 0, 255),
            'meta' => $meta,
        ]);

        Log::info('sso.'.$type, [
            'user_id' => $userId,
            'ip' => $request->ip(),
            'ua' => substr((string) $request->userAgent(), 0, 200),
            'meta' => $meta,
        ]);
    }
}
