<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\UserRole;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class TestAuthController extends Controller
{
    /**
     * Generate a test token for development
     *
     * NOTE: This endpoint should be REMOVED or DISABLED in production!
     */
    public function generateToken(Request $request)
    {
        // Validate request
        $validator = Validator::make($request->all(), [
            'email' => 'required|email',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'message' => 'Validation failed',
                'errors' => $validator->errors(),
            ], 422);
        }

        // Find the user role
        $userRole = UserRole::where('email', $request->email)
            ->where('is_active', true)
            ->first();

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

        // Update last login
        $userRole->last_login_at = now();
        $userRole->save();

        // Generate token (expires in 30 days as per sanctum config)
        $token = $userRole->createToken('test-token')->plainTextToken;

        return response()->json([
            'message' => 'Token generated successfully',
            'access_token' => $token,
            'token_type' => 'Bearer',
            'user' => [
                'email' => $userRole->email,
                'role' => $userRole->role,
                'is_active' => $userRole->is_active,
            ],
        ]);
    }

    /**
     * Get current authenticated user (for testing)
     */
    public function me(Request $request)
    {
        $user = $request->user();

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

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

    /**
     * Revoke current token (logout)
     */
    public function revokeToken(Request $request)
    {
        $user = $request->user();

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

        // Revoke current token
        $request->user()->currentAccessToken()->delete();

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

    /**
     * List all available test users
     */
    public function listTestUsers()
    {
        $users = UserRole::where('email', 'like', '%@beyti.test')
            ->where('is_active', true)
            ->get(['email', 'role', 'is_active', 'last_login_at']);

        return response()->json([
            'message' => 'Test users retrieved successfully',
            'users' => $users,
            'note' => 'Use POST /api/test/token with any of these emails to get an access token',
        ]);
    }
}
