using Microsoft.AspNetCore.Mvc;
using backend.Application;
using backend.Models;
using System.Text.Json.Nodes;
using Microsoft.AspNetCore.Identity;

namespace backend.Controllers;

[ApiController]
public class UserController : ControllerBase
{
    [HttpPost("Register")]
    public IActionResult Register([FromBody] JsonObject input)
    {
        if (input["username"] == null || input["password"] == null) {
            return BadRequest("Username and password required");
        }

        var passwordHasher = new PasswordHasher<object>();
        string hashedPassword = passwordHasher.HashPassword(null, input["password"]!.ToString());

        string touchCode = "";
        for (int i = 0; i < 4; i++) {
            touchCode += (1 + new Random().Next() % 5).ToString();
        }

        var user = new User {
            Username = input["username"]!.ToString(),
            Password = hashedPassword,
            TouchCode = touchCode,
        };

		ApplicationState.DbContext!.Add(user);
		ApplicationState.DbContext!.SaveChanges();

        Console.WriteLine("Created user: " + user.Username);

        return Ok();
    }
}
