using Microsoft.AspNetCore.Mvc;
using khmer_eid_backend.Integrations.Ory;
using khmer_eid_backend.Requests;
using Microsoft.AspNetCore.Authorization;

namespace khmer_eid_backend.Controllers
{
    [ApiController]
    [Route("auth")]
    public class AuthController(KratosIntegration _kratos) : ControllerBase
    {
        [HttpPost("request-signup-otp")]
        public async Task<IActionResult> RequestSignupOtp([FromForm] SignupRequest request)
        {
            var data = await _kratos.CreateOtpRegistrationFlowAsync(phone: request.Phone);
            return Ok(new { Message = "OTP sent if the phone number is valid.", data });
        }

        [HttpPost("verify-signup-otp")]
        public async Task<IActionResult> VerifySignupOtp([FromForm] string phone,[FromForm] string otp, [FromForm] string flowId)
        {
            var data = await _kratos.CompleteOtpRegistrationFlowAsync(flowId, phone, otp);
            return Ok(new { Message = "OTP verified successfully.", data });
        }

        [HttpPost("request-login-otp")]
        public async Task<IActionResult> RequestLoginOtp([FromForm] string phone)
        {
            var data = await _kratos.CreateOtpLoginFlowAsync(phone: phone);
            return Ok(new { Message = "OTP sent if the phone number is valid.", data });
        }

        [HttpPost("verify-login-otp")]
        public async Task<IActionResult> VerifyLoginOtp([FromForm] string phone, [FromForm] string otp, [FromForm] string flowId)
        {
            var data = await _kratos.CompleteOtpLoginFlowAsync(flowId, phone, otp);
            return Ok(new { Message = "OTP verified successfully.", data });
        }

        [HttpPost("logout")]
        [Authorize(AuthenticationSchemes = "Kratos")]
        public async Task<IActionResult> Logout()
        {
            var data = await _kratos.Logout(Request.Headers.Authorization.ToString().Replace("Bearer ",""));
            return Ok(new { Message = "Logged out successfully."});
        }
    }
}
