using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using MilitaryTrainingManagement.Models.DTOs;
using MilitaryTrainingManagement.Services.Interfaces;

namespace MilitaryTrainingManagement.Controllers;

/// <summary>
/// 认证控制器
/// </summary>
[Route("api/admin/auth")]
public class AuthController : BaseApiController
{
    private readonly IAuthenticationService _authService;

    public AuthController(IAuthenticationService authService)
    {
        _authService = authService;
    }

    [HttpPost("login")]
    [AllowAnonymous]
    public async Task<IActionResult> Login([FromBody] LoginRequest request)
    {
        var (user, token) = await _authService.LoginAsync(request.Username, request.Password);
        if (user == null || token == null)
        {
            return Unauthorized(new { message = "用户名或密码错误" });
        }

        return Ok(new LoginResponse
        {
            Token = token,
            UserId = user.Id,
            Username = user.Username,
            DisplayName = user.DisplayName,
            OrganizationalUnitId = user.OrganizationalUnitId,
            OrganizationalUnitName = user.OrganizationalUnit.Name,
            OrganizationalLevel = user.OrganizationalUnit.Level
        });
    }

    [HttpPost("logout")]
    [Authorize]
    public IActionResult Logout()
    {
        return Ok(new { message = "登出成功" });
    }

    [HttpGet("profile")]
    [Authorize]
    public async Task<IActionResult> GetProfile()
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return Unauthorized();
        }

        var user = await _authService.GetUserByIdAsync(userId.Value);
        if (user == null)
        {
            return NotFound();
        }

        return Ok(new UserProfileResponse
        {
            UserId = user.Id,
            Username = user.Username,
            DisplayName = user.DisplayName,
            OrganizationalUnitId = user.OrganizationalUnitId,
            OrganizationalUnitName = user.OrganizationalUnit.Name,
            OrganizationalLevel = user.OrganizationalUnit.Level
        });
    }
}
