@page "/register"
@* Virtual route to trick blazor *@

@using Moonlight.App.Services
@using Moonlight.App.Models.Forms
@using Moonlight.App.Services.Users
@using Moonlight.App.Exceptions
@using Moonlight.App.Models.Forms.Auth

@inject IdentityService IdentityService
@inject UserService UserService
@inject CookieService CookieService
@inject NavigationManager Navigation

<div class="w-100">
    <div class="card-body">
        <div class="text-start mb-8">
            <h1 class="text-dark mb-3 fs-3x">
                Sign Up
            </h1>
            <div class="text-gray-400 fw-semibold fs-6">
                Get unlimited access &amp; earn money
            </div>
        </div>

        <SmartForm Model="Form" OnValidSubmit="OnValidSubmit">
            <div class="fv-row mb-8">
                <input @bind="Form.Username" type="text" placeholder="Username" class="form-control form-control-solid">
            </div>

            <div class="fv-row mb-8">
                <input @bind="Form.Email" type="text" placeholder="Email" class="form-control form-control-solid">
            </div>

            <div class="fv-row mb-7">
                <input @bind="Form.Password" type="password" placeholder="Password" class="form-control form-control-solid">
            </div>

            <div class="fv-row mb-7">
                <input @bind="Form.RepeatedPassword" type="password" placeholder="Repeat your password" class="form-control form-control-solid">
            </div>

            <div class="d-flex flex-stack flex-wrap gap-3 fs-base fw-semibold mb-10">
                <div></div>
                <a href="/login" class="link-primary">
                    Already have an account ?
                </a>
            </div>

            <div class="d-flex flex-stack">
                <button type="submit" class="btn btn-primary me-2 flex-shrink-0">Sign Up</button>
                <div class="d-flex align-items-center">
                    <div class="text-gray-400 fw-semibold fs-6 me-3 me-md-6">Or</div>
                    @* OAuth2 Providers here *@
                </div>
            </div>
        </SmartForm>
    </div>
</div>

@code
{
    private RegisterForm Form = new();

    private async Task OnValidSubmit()
    {
        if (Form.Password != Form.RepeatedPassword)
            throw new DisplayException("The passwords do not match");

        var user = await UserService.Auth.Register(Form.Username, Form.Email, Form.Password);
        var token = await IdentityService.GenerateToken(user);

        await CookieService.SetValue("token", token);
        await IdentityService.Authenticate(token);

        if (Navigation.Uri.EndsWith("/register"))
            Navigation.NavigateTo("/");
    }
}