using FamilyTreeAPI.Interface;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using FamilyTreeAPI.Entities;
namespace FamilyTreeAPI.Controllers;

[Authorize]
[ApiController]
[Route("api/[controller]")]
public class UsersController : ControllerBase
{
    private readonly IUserService _userService;
    
    public UsersController(IUserService userService)
    {
        _userService = userService;
    }
    
    [AllowAnonymous]
    [HttpPost("[action]")]
    public async Task<IActionResult> Login([FromBody] AuthenticateRequest model)
    {
        string remoteIpAddress = HttpContext.Connection.RemoteIpAddress?.ToString();
        var response = await _userService.Login(model);
        return Ok(response);
    }

    //[AllowAnonymous]
    //[HttpPost("[action]")]
    //public async Task<IActionResult> LoginAD(AuthenticateRequest model)
    //{
    //    var response = await _userService.LoginAD(model);
    //    return Ok(response);
    //}
    [AllowAnonymous]
    [HttpPost("[action]")]
    public async Task<IActionResult> LoginApiAD([FromBody] AuthenticateRequest model)
    {
        string remoteIpAddress = HttpContext.Connection.RemoteIpAddress?.ToString();
        var response = await _userService.LoginApiAD(model, remoteIpAddress);
        return Ok(response);
    }

    [HttpPost("[action]")]
    public async Task<IActionResult> Logout()
    {
        var currentUser = (UserDto)HttpContext.Items["User"];
        if (null == currentUser)
            return Unauthorized(new { message = "Unauthorized" });

        string token = Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last();
        string remoteIpAddress = Request.HttpContext.Connection.RemoteIpAddress.ToString();
        var response = await _userService.Logout(token, currentUser, remoteIpAddress);
        return Ok(response);
    }

    //[AllowAnonymous]
    //[HttpGet("[action]")]
    //public async Task<IActionResult> SearchADStaff(string stafflinkNo)
    //{
    //    var user = await _userService.SearchADStaff(stafflinkNo);
    //    return Ok(user);
    //}
    /*
    [AllowAnonymous]
    [HttpGet("[action]")]
    public async Task<ResultModel<User>> SearchADStaff(string stafflinkNo) 
    {
        var user = await _userService.SearchADStaff(stafflinkNo);
        return user;
    }
    */
}
