using AssetManager.API.DTOs;
using AssetManager.Models;
using AssetManager.Services.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.Threading.Tasks;

namespace AssetManager.API.Controllers;

[ApiController]
[Route("api/[controller]")]
public class AuthController : ControllerBase
{
    private readonly ILogger<AuthController> _logger;
    private readonly WechatService _wechatService;
    private readonly JwtService _jwtService;

    public AuthController(ILogger<AuthController> logger, WechatService wechatService, JwtService jwtService)
    {
        _logger = logger;
        _wechatService = wechatService;
        _jwtService = jwtService;
    }

    [HttpPost("login")]
    public ActionResult<ApiResponse<LoginResponse>> Login([FromBody] LoginRequest request)
    {
        try
        {
            _logger.LogInformation($"Login attempt for user: {request.Email}");
            
            // 模拟登录验证
            if (request.Email == "test@example.com" && request.Password == "password123")
            {
                // 生成真实的JWT令牌
                var token = _jwtService.GenerateToken("1", "Test User", request.Email);
                
                var response = new LoginResponse
                {
                    Token = token,
                    ExpireAt = DateTime.Now.AddHours(24).ToString("yyyy-MM-dd HH:mm:ss"),
                    User = new UserBasicInfo
                    {
                        UserName = "Test User",
                        Email = request.Email
                    }
                };

                _logger.LogInformation($"Login successful for user: {request.Email}");
                
                return Ok(new ApiResponse<LoginResponse>
                {
                    Code = AssetManager.Models.StatusCodes.Success,
                    Data = response,
                    Message = "Login successful"
                });
            }

            _logger.LogWarning($"Login failed for user: {request.Email}");
            
            return Unauthorized(new ApiResponse<LoginResponse>
            {
                Code = AssetManager.Models.StatusCodes.Unauthorized,
                Data = null,
                Message = "Invalid email or password"
            });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error during login");
            
            return StatusCode(AssetManager.Models.StatusCodes.InternalServerError, new ApiResponse<LoginResponse>
            {
                Code = AssetManager.Models.StatusCodes.InternalServerError,
                Data = null,
                Message = ex.Message
            });
        }
    }

    [HttpPost("wechat-login")]
    public async Task<ActionResult<ApiResponse<WechatLoginResponse>>> WechatLogin([FromBody] WechatLoginRequest request)
    {
        try
        {
            _logger.LogInformation("Wechat login attempt");
            
            // 用code换取openid
            var authResult = await _wechatService.GetOpenIdAsync(request.Code);
            
            if (authResult.Errcode != 0)
            {
                _logger.LogWarning($"Wechat login failed: {authResult.Errmsg}");
                return Unauthorized(new ApiResponse<WechatLoginResponse>
                {
                    Code = AssetManager.Models.StatusCodes.Unauthorized,
                    Data = null,
                    Message = authResult.Errmsg
                });
            }
            
            // 生成真实的JWT令牌
            var token = _jwtService.GenerateToken(authResult.OpenId, request.NickName ?? "Wechat User", $"{authResult.OpenId}@wechat.com");
            
            var response = new WechatLoginResponse
            {
                Token = token,
                ExpireAt = DateTime.Now.AddHours(24).ToString("yyyy-MM-dd HH:mm:ss"),
                User = new UserBasicInfo
                {
                    UserName = request.NickName ?? "Wechat User",
                    Email = $"{authResult.OpenId}@wechat.com"
                },
                OpenId = authResult.OpenId
            };

            _logger.LogInformation($"Wechat login successful for user: {authResult.OpenId}");
            
            return Ok(new ApiResponse<WechatLoginResponse>
            {
                Code = AssetManager.Models.StatusCodes.Success,
                Data = response,
                Message = "Wechat login successful"
            });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error during wechat login");
            
            return StatusCode(AssetManager.Models.StatusCodes.InternalServerError, new ApiResponse<WechatLoginResponse>
            {
                Code = AssetManager.Models.StatusCodes.InternalServerError,
                Data = null,
                Message = ex.Message
            });
        }
    }

    [HttpPost("register")]
    public ActionResult<ApiResponse<RegisterResponse>> Register([FromBody] RegisterRequest request)
    {
        try
        {
            _logger.LogInformation($"Registration attempt for user: {request.Email}");
            
            // 模拟注册
            var response = new RegisterResponse
            {
                Id = Guid.NewGuid().ToString(),
                Status = "success"
            };

            _logger.LogInformation($"Registration successful for user: {request.Email}");
            
            return Ok(new ApiResponse<RegisterResponse>
            {
                Code = AssetManager.Models.StatusCodes.Success,
                Data = response,
                Message = "Registration successful"
            });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error during registration");
            
            return StatusCode(AssetManager.Models.StatusCodes.InternalServerError, new ApiResponse<RegisterResponse>
            {
                Code = AssetManager.Models.StatusCodes.InternalServerError,
                Data = null,
                Message = ex.Message
            });
        }
    }
}