namespace Brizco.Api.Controllers;

public class AuthController : ICarterModule
{

    public virtual void AddRoutes(IEndpointRouteBuilder app)
    {
        var group = app.NewVersionedApi("Auth")
            .MapGroup($"api/auth");

        group.MapPost("login/password", LoginWithPassword)
            .WithDisplayName("LoginWithPassword")
            .HasApiVersion(1.0);
        group.MapPost("login/swagger", LoginSwagger)
            .WithDisplayName("LoginSwagger")
            .HasApiVersion(1.0);

        group.MapPost("login/code", LoginWithVerifyCode)
            .WithDisplayName("LoginWithVerifyCode")
            .HasApiVersion(1.0);

        group.MapGet("verifycode", GetVerifyCodeCode)
            .WithDisplayName("GetVerifyCodeCode")
            .HasApiVersion(1.0);

        group.MapPut("forget/password", ForgetPassword)
            .WithDisplayName("ForgetPassword")
            .HasApiVersion(1.0);

        group.MapPost("signup/complex", SignUpComplex)
            .WithDisplayName("SignUp")
            .RequireAuthorization(builder =>  builder.AddAuthenticationSchemes("Bearer").RequireAuthenticatedUser())
            .HasApiVersion(1.0);
    }

    public async Task<IResult> SignUpComplex([FromBody] SignUpRequestDto request, IAccountService accountService, CancellationToken cancellationToken) =>
        TypedResults.Ok(await accountService.CompleteComplexSignUpAsync(request,cancellationToken));

    public async Task<IResult> LoginWithPassword([FromBody] LoginRequestDto loginRequestDto,IAccountService accountService, CancellationToken cancellationToken) => 
        TypedResults.Ok(await accountService.LoginWithPasswordAsync(loginRequestDto.UserName, loginRequestDto.Password,cancellationToken));


    public async Task<IResult> LoginWithVerifyCode([FromBody] LoginRequestDto loginRequestDto, IAccountService accountService, CancellationToken cancellationToken) =>
        TypedResults.Ok(await accountService.LoginWithVerifyCodeAsync(loginRequestDto.UserName, loginRequestDto.VerifyCode,cancellationToken));


    public async Task<IResult> GetVerifyCodeCode([FromQuery] string phoneNumber, IAccountService accountService) =>
        TypedResults.Ok(await accountService.GetVerifyCodeAsync(phoneNumber));


    public async Task<IResult> ForgetPassword([FromQuery] string phoneNumber, IAccountService accountService) =>
        TypedResults.Ok(await accountService.ForgetPasswordAsync(phoneNumber));


    public async Task<IResult> LoginSwagger(HttpContext ctx, IAccountService accountService, CancellationToken cancellationToken)
    {

        var username = ctx.Request.Form["username"];
        var password = ctx.Request.Form["password"];
        return TypedResults.Json(await accountService.LoginWithPasswordAsync(username, password, cancellationToken));
    }


}