using DiunaBI.API.Services;
using DiunaBI.Domain.Entities;
using Microsoft.AspNetCore.Mvc;

namespace DiunaBI.API.Controllers;

[ApiController]
[Route("[controller]")]
public class AuthController(
    GoogleAuthService googleAuthService,
    JwtTokenService jwtTokenService,
    ILogger<AuthController> logger)
    : ControllerBase
{
    [HttpPost("apiToken")]
    public async Task<IActionResult> ApiToken([FromBody] string idToken)
    {
        try
        {
            if (string.IsNullOrEmpty(idToken))
            {
                logger.LogWarning("Empty idToken received");
                return BadRequest("IdToken is required");
            }
            
            var (isValid, user, error) = await googleAuthService.ValidateGoogleTokenAsync(idToken);

            if (!isValid || user == null)
            {
                logger.LogWarning("Google token validation failed: {Error}", error);
                return Unauthorized();
            }
            
            var jwt = jwtTokenService.GenerateToken(user);

            logger.LogInformation("User authenticated successfully: {Email}", user.Email);

            return Ok(new
            {
                token = jwt,
                id = user.Id,
                expirationTime = DateTime.UtcNow.AddDays(7) // z JwtSettings
            });
        }
        catch (Exception ex)
        {
            logger.LogError(ex, "Error during authentication");
            return StatusCode(500, "Internal server error");
        }
    }
}