using Microsoft.AspNetCore.Mvc;
using BoredCareers.Services.DatabaseService;
using BoredCareers.Entities;
using System.Text.Json;
using System.Text;

namespace BoredCareers.Controllers {
    [ApiController]
    [Route("api/account/")]
    public class AuthenticationController : MistoxControllerBase {

        public AuthenticationController(DatabaseService db) : base(db) { }

        [HttpPost("loginstate")]
        public ActionResult<Account> LoginState() {
            if (isLoggedIn()) {
                return Ok(getLoggedInUser());
            }
            return NotFound("Not logged in");
        }

        [HttpPost("loginticket")]
        public async Task<ActionResult> LoginTicket([FromBody] string LoginToken) {
            using (HttpClient client = new HttpClient()) {
                var payload = new { ticket = LoginToken };
                StringContent jsonPayload = new StringContent(JsonSerializer.Serialize(payload), Encoding.UTF8, "application/json");
                HttpResponseMessage JWTResponse = await client.PostAsync("https://auth.mistox.com/api/auth/token", jsonPayload);
                if (JWTResponse.IsSuccessStatusCode) {
                    string JWT = await JWTResponse.Content.ReadAsStringAsync();
                    signIn(JWT);
                    return Ok();
                } else {
                    string error = await JWTResponse.Content.ReadAsStringAsync();
                    return NotFound(error);
                }
            }
        }

        [HttpGet("logout")]
        public ActionResult Logout() {
            if (isLoggedIn()) {
                signOut();
                return Redirect("/");
            }
            return NotFound("Not logged in");
        }

    }

}
