using HotelPosApi.Data;
using HotelPosApi.DTOs;
using HotelPosApi.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace HotelPosApi.Controllers;

[ApiController]
[Route("api/[controller]")]
public class AuthController : ControllerBase
{
    private readonly AppDbContext _db;
    private readonly JwtTokenService _jwt;
    private readonly PasswordHasher<string> _hasher = new();

    public AuthController(AppDbContext db, JwtTokenService jwt)
    {
        _db = db;
        _jwt = jwt;
    }

    [HttpPost("login")]
    [AllowAnonymous]
    public async Task<ActionResult<LoginResponse>> Login([FromBody] LoginRequest req)
    {
        if (string.IsNullOrWhiteSpace(req.Username) || string.IsNullOrWhiteSpace(req.Password))
            return BadRequest("Username and password required.");

        var user = await _db.Users.FirstOrDefaultAsync(u => u.Username == req.Username);
        if (user == null)
            return Unauthorized();

        var verify = _hasher.VerifyHashedPassword(req.Username, user.PasswordHash, req.Password);
        if (verify != PasswordVerificationResult.Success)
            return Unauthorized();

        var (token, expires) = _jwt.CreateToken(user.Username, user.Role);

        return Ok(new LoginResponse
        {
            Token = token,
            Username = user.Username,
            Role = user.Role,
            ExpiresAtUtc = expires,
        });
    }

    [HttpGet("me")]
    [Authorize]
    public IActionResult Me()
    {
        var name = User.FindFirst(System.Security.Claims.ClaimTypes.Name)?.Value;
        var role = User.FindFirst(System.Security.Claims.ClaimTypes.Role)?.Value;
        return Ok(new { username = name, role });
    }
}
