using BukiVedi.App.Requests;
using BukiVedi.App.Responces;
using BukiVedi.Shared.Models;
using BukiVedi.Shared.Services;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;

namespace BukiVedi.App.Controllers
{
    [ApiController]
    public class AuthController
       : BaseController
    {
        public AuthController()
            : base()
        {

        }

        /// <summary>
        /// Аутентификация на сайте через логин пароль
        /// </summary>
        /// <param name="request">Логин/пароль</param>
        /// <returns></returns>
        [HttpPost("/api/auth")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        public async Task<ActionResult<AutoCodeResponse>> SignIn([FromBody] AuthLPRequest request)
        {
            var acc = await OperationContext.AuthProvider.GetAccount(request?.Login!, request?.Password!);
            if (acc == null)
            {
                return Ok(new AutoCodeResponse { Success = false, ReasonPhrase = "Аккаунт не найден" });
            }
            var token = UserTokenGenerator.GenerateUserToken(acc);

            var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme,
                        ClaimTypes.Name, ClaimTypes.Role);
            identity.AddClaim(new Claim("Subject", acc.Login));
            identity.AddClaim(new Claim("Token", token));
            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, 
                new ClaimsPrincipal(identity), 
                new AuthenticationProperties 
                {
                    IsPersistent = true
                });

            return Ok(new AutoCodeResponse
            {
                Success = true
            });
        }
    }
}
