using Hc900Crawler.Infrastructure.Kb;
using Microsoft.AspNetCore.Mvc;

namespace Hc900Crawler.Web.Controllers;

[ApiController]
[Route("api/kb/auth")]
public class KbAuthController : ControllerBase
{
    private readonly IKbAuthService _auth;
    private readonly ILogger<KbAuthController> _logger;

    public KbAuthController(IKbAuthService auth, ILogger<KbAuthController> logger)
    {
        _auth = auth;
        _logger = logger;
    }

    public sealed record LoginRequest(string Password);
    public sealed record ChangePasswordRequest(string OldPassword, string NewPassword);

    [HttpPost("login")]
    public async Task<IActionResult> Login([FromBody] LoginRequest req, CancellationToken ct)
    {
        if (req == null || string.IsNullOrWhiteSpace(req.Password))
            return Ok(new { success = false, error = "password is required" });

        var ip = HttpContext.Connection.RemoteIpAddress?.ToString();
        var result = await _auth.LoginAsync(req.Password, ip, ct);
        if (!result.Success)
            return Ok(new { success = false, error = result.Error ?? "login failed" });

        return Ok(new { success = true, token = result.Token, expiresAt = result.ExpiresAt });
    }

    [HttpPost("logout")]
    public async Task<IActionResult> Logout(CancellationToken ct)
    {
        var token = Request.Headers["X-Kb-Token"].ToString();
        if (!string.IsNullOrEmpty(token))
            await _auth.LogoutAsync(token, ct);
        return Ok(new { success = true });
    }

    [HttpGet("status")]
    public async Task<IActionResult> Status(CancellationToken ct)
    {
        var token = Request.Headers["X-Kb-Token"].ToString();
        var valid = await _auth.ValidateAsync(token, ct);
        return Ok(new { valid });
    }

    [HttpPost("change-password")]
    public async Task<IActionResult> ChangePassword([FromBody] ChangePasswordRequest req, CancellationToken ct)
    {
        var token = Request.Headers["X-Kb-Token"].ToString();
        if (!await _auth.ValidateAsync(token, ct))
            return Unauthorized(new { success = false, error = "invalid token" });

        if (req == null || string.IsNullOrWhiteSpace(req.OldPassword) || string.IsNullOrWhiteSpace(req.NewPassword))
            return Ok(new { success = false, error = "passwords required" });
        if (req.NewPassword.Length < 6)
            return Ok(new { success = false, error = "new password must be at least 6 chars" });

        var ok = await _auth.ChangePasswordAsync(req.OldPassword, req.NewPassword, ct);
        return Ok(new { success = ok });
    }
}
