using System.Security.Claims;
using Bimix.API.Services;
using Bimix.Application.DTOModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace Bimix.API.Controllers;

public class AuthController(
    GoogleAuthService googleAuthService,
    JwtTokenService jwtTokenService,
    ILogger<AuthController> logger)
    : ControllerBase
{
    [HttpPost("google")]
    public async Task<IActionResult> GoogleAuth([FromBody] GoogleAuthRequest request)
    {
        try
        {
            if (string.IsNullOrEmpty(request.IdToken))
            {
                return BadRequest(new GoogleAuthResponse
                {
                    Success = false,
                    Error = "IdToken is required"
                });
            }

            var (isValid, user, error) = await googleAuthService.ValidateGoogleTokenAsync(request.IdToken);

            if (!isValid || user == null)
            {
                var statusCode = error switch
                {
                    "User not authorized to access this application" => 403,
                    "User account is not active" => 403,
                    "Invalid Google token" => 401,
                    _ => 401
                };
                
                return StatusCode(statusCode, new GoogleAuthResponse
                {
                    Success = false,
                    Error = error ?? "Authentication failed"
                });
            }

            var jwt = jwtTokenService.GenerateToken(user);

            return Ok(new GoogleAuthResponse
            {
                Success = true,
                Token = jwt,
                User = new UserDto
                {
                    Id = user.Id,
                    Email = user.Email,
                    FullName = user.FullName,
                    IsActive = user.IsActive,
                    LastLoginAt = user.LastLoginAt
                }
            });
        }
        catch (Exception ex)
        {   
            logger.LogError(ex, "Error during Google authentication");
            return StatusCode(500, new GoogleAuthResponse
            {
                Success = false,
                Error = "Internal server error"
            });
        }
    }

    [HttpGet("me")]
    [Authorize]
    public IActionResult GetCurrentUser()
    {
        var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier);
        var emailClaim = User.FindFirst(ClaimTypes.Email);
        var nameClaim = User.FindFirst(ClaimTypes.Name);
        
        if (userIdClaim == null || emailClaim == null || nameClaim == null)
        {
            return Unauthorized();
        }
        
        return Ok(new UserDto
        {
            Id = Guid.Parse(userIdClaim.Value),
            Email = emailClaim.Value,
            FullName = nameClaim.Value,
            IsActive = true,
        });
    }
}