using BCrypt.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Aeldria.Api.Data;
using Aeldria.Api.DTOs;
using Aeldria.Api.Models;
using Aeldria.Api.Services;

namespace Aeldria.Api.Controllers;

[ApiController]
[Route("api/auth")]
public class AuthController : ControllerBase
{
    private readonly AeldriaDbContext _db;
    private readonly JwtService _jwt;

    public AuthController(AeldriaDbContext db, JwtService jwt)
    {
        _db = db;
	_jwt = jwt;
    }

    [HttpPost("register")]
    public async Task<IActionResult> Register(RegisterRequest request)
    {
        if (await _db.Accounts.AnyAsync(x => x.Username == request.Username))
            return BadRequest("Nom d'utilisateur déjà utilisé.");

        if (await _db.Accounts.AnyAsync(x => x.Email == request.Email))
            return BadRequest("Email déjà utilisé.");

        var account = new Account
        {
            Username = request.Username,
            Email = request.Email,
            PasswordHash = PasswordService.HashPassword(request.Password),
            CreatedAt = DateTime.UtcNow,
            IsBanned = false,
            IsVerified = false
        };

        _db.Accounts.Add(account);
        await _db.SaveChangesAsync();
	
        return Ok(new
        {
            Message = "Compte créé avec succès.",
            AccountId = account.AccountId
        });
    }

    [HttpPost("login")]
    public async Task<IActionResult> Login(LoginRequest request)
    {
        var account = await _db.Accounts
            .FirstOrDefaultAsync(x => x.Username == request.Username);

        if (account == null)
            return Unauthorized("Compte introuvable.");

        if (!PasswordService.VerifyPassword(request.Password, account.PasswordHash))
            return Unauthorized("Mot de passe incorrect.");

        account.LastLogin = DateTime.UtcNow;
        await _db.SaveChangesAsync();
	var token = _jwt.GenerateToken(account);
        return Ok(new
        {
            Message = "Connexion réussie.",
            AccountId = account.AccountId,
            Username = account.Username,
	    Token = token
        });
    }
}
