using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using ReallifeGamemode.Database.Entities;
using ReallifeGamemode.Database.Models;
using ReallifeGamemode.DataService.Logic;
using ReallifeGamemode.DataService.Types;

namespace ReallifeGamemode.DataService.Controllers
{
  [ApiController]
  [Produces("application/json")]
  [Route("DataService/Auth")]
  public class AuthController : ControllerBase
  {
    private readonly JwtTokenGenerator tokenGenerator;
    private readonly DatabaseContext dbContext;

    public AuthController(JwtTokenGenerator tokenGenerator, DatabaseContext dbContext)
    {
      this.tokenGenerator = tokenGenerator;
      this.dbContext = dbContext;
    }

    [HttpPost("Login")]
    public ActionResult<LoginResponse> Login(LoginRequest request)
    {
      string hashedPassword = ComputeSha256Hash(request.Password);
      User user = dbContext.Users.Where(u => u.Name == request.Username && u.Password == hashedPassword).FirstOrDefault();

      string token = tokenGenerator.GenerateUserToken(user);

      if (string.IsNullOrEmpty(token))
      {
        return Unauthorized();
      }

      return new LoginResponse()
      {
        Token = token
      };
    }

    private string ComputeSha256Hash(string rawData)
    {
      // Create a SHA256   
      using (SHA256 sha256Hash = SHA256.Create())
      {
        // ComputeHash - returns byte array  
        byte[] bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(rawData));

        // Convert byte array to a string   
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < bytes.Length; i++)
        {
          builder.Append(bytes[i].ToString("x2"));
        }
        return builder.ToString();
      }
    }
  }
}
