using DiunaBI.Domain.Entities;
using DiunaBI.Infrastructure.Data;
using Google.Apis.Auth;
using Microsoft.EntityFrameworkCore;

namespace DiunaBI.API.Services;

public class GoogleAuthService(AppDbContext context, IConfiguration configuration, ILogger<GoogleAuthService> logger)
{
    private readonly AppDbContext _context = context;
    private readonly IConfiguration _configuration = configuration;
    private readonly ILogger<GoogleAuthService> _logger = logger;

    public async Task<(bool IsValid, User? user, string? error)> ValidateGoogleTokenAsync(string idToken)
    {
        try
        {
            var clientId = _configuration["GoogleAuth:ClientId"];
            if (string.IsNullOrEmpty(clientId))
            {
                _logger.LogError("Google Auth Client Id is not configured");
                return (false, null, "Google Auth Client Id is not configured");
            }

            var payload = await GoogleJsonWebSignature.ValidateAsync(idToken,
                new GoogleJsonWebSignature.ValidationSettings
                {
                    Audience = new[] { clientId }
                });

            _logger.LogInformation("Google token validated for user: {Email}", payload.Email);
            
            var user = await _context.Users
                .FirstOrDefaultAsync(x => x.Email == payload.Email);

            if (user == null)
            {
                _logger.LogError("User not found in DiunaBI database: {Email}", payload.Email);
                return (false, null, "User not found in DiunaBI database");
            }
            
            user.UserName = payload.Name;
            
            await _context.SaveChangesAsync();
            
            _logger.LogInformation("User logged in: {Email}", payload.Email);
            
            return (true, user, null);
        }
        catch (InvalidJwtException ex)
        {
            _logger.LogError(ex, "Invalid JWT token");
            return (false, null, "Invalid JWT token");
        } catch (Exception ex)
        {
            _logger.LogError(ex, "Error validating Google token");
            return (false, null, "Error validating Google token");
        }
    }
}