using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SIGCM.Application.DTOs;
using SIGCM.Application.Interfaces;
using SIGCM.Infrastructure.Repositories;
using SIGCM.Domain.Entities;

namespace SIGCM.API.Controllers;

[ApiController]
[Route("api/[controller]")]
public class AuthController : ControllerBase
{
    private readonly IAuthService _authService;
    private readonly AuditRepository _auditRepo;

    public AuthController(IAuthService authService, AuditRepository auditRepo)
    {
        _authService = authService;
        _auditRepo = auditRepo;
    }

    // Inicio de sesión tradicional
    [HttpPost("login")]
    public async Task<IActionResult> Login(LoginDto dto)
    {
        var result = await _authService.LoginAsync(dto.Username, dto.Password);
        if (!result.Success) return Unauthorized(new { message = result.ErrorMessage });

        // Audit Log
        if (result.UserId.HasValue)
        {
            await _auditRepo.AddLogAsync(new AuditLog
            {
                UserId = result.UserId.Value,
                Action = "LOGIN",
                EntityId = result.UserId.Value,
                EntityType = "User",
                Details = $"Inicio de sesión exitoso: {dto.Username}",
                CreatedAt = DateTime.UtcNow
            });
        }

        return Ok(result);
    }

    // Registro de nuevos usuarios
    [HttpPost("register")]
    public async Task<IActionResult> Register(RegisterDto dto)
    {
        var result = await _authService.RegisterAsync(dto.Username, dto.Email, dto.Password);
        if (!result.Success) return BadRequest(new { message = result.ErrorMessage });
        return Ok(result);
    }

    // Inicio de sesión con Google
    [HttpPost("google-login")]
    public async Task<IActionResult> GoogleLogin([FromBody] string idToken)
    {
        var result = await _authService.GoogleLoginAsync(idToken);
        if (!result.Success) return Unauthorized(new { message = result.ErrorMessage });
        return Ok(result);
    }

    // Flujo MFA: Obtener secreto (QR)
    [Authorize]
    [HttpGet("mfa/setup")]
    public async Task<IActionResult> SetupMfa()
    {
        var userId = int.Parse(User.FindFirst("Id")?.Value!);
        var secret = await _authService.GenerateMfaSecretAsync(userId);
        return Ok(new { secret, qrCodeUri = $"otpauth://totp/SIGCM:{User.Identity?.Name}?secret={secret}&issuer=SIGCM" });
    }

    // Flujo MFA: Verificar y activar
    [Authorize]
    [HttpPost("mfa/verify")]
    public async Task<IActionResult> VerifyMfa([FromBody] string code)
    {
        var userId = int.Parse(User.FindFirst("Id")?.Value!);
        var valid = await _authService.VerifyMfaCodeAsync(userId, code);
        if (!valid) return BadRequest(new { message = "Código inválido" });
        
        await _authService.EnableMfaAsync(userId, true);

        // Audit Log
        await _auditRepo.AddLogAsync(new AuditLog
        {
            UserId = userId,
            Action = "ENABLE_MFA",
            EntityId = userId,
            EntityType = "User",
            Details = "Autenticación de Dos Factores activada",
            CreatedAt = DateTime.UtcNow
        });

        return Ok(new { success = true });
    }
}

public class RegisterDto
{
    public string Username { get; set; } = "";
    public string Email { get; set; } = "";
    public string Password { get; set; } = "";
}
