using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;

public class AuthService : IAuthService
{
    private readonly AppDbContext _db;
    private readonly JwtOptions _jwt;

    public AuthService(AppDbContext db, IOptions<JwtOptions> jwt)
    {
        _db = db;
        _jwt = jwt.Value;
    }

    public async Task<LoginResponse> LoginAsync(LoginRequest req)
    {
        var user = await _db.ClinicalUsers
            .FirstOrDefaultAsync(u => u.Username == req.Username && u.IsActive);

        if (user is null || !BCrypt.Net.BCrypt.Verify(req.Password, user.PasswordHash))
            throw new ValidationException("Invalid username or password.", "INVALID_CREDENTIALS");

        user.LastLoginAt = DateTimeOffset.UtcNow;
        await _db.SaveChangesAsync();

        _db.ClinicalAuditLogs.Add(new ClinicalAuditLog
        {
            Id = Guid.NewGuid(),
            Action = AuditAction.UserLogin,
            EntityType = "ClinicalUser",
            EntityId = user.Id,
            UserId = user.Id,
            UserDisplayName = user.DisplayName,
            CreatedAt = DateTimeOffset.UtcNow
        });
        await _db.SaveChangesAsync();

        var expires = DateTimeOffset.UtcNow.AddMinutes(_jwt.ExpirationMinutes);
        var accessToken = GenerateAccessToken(user, expires);
        var refreshToken = await CreateRefreshTokenAsync(user.Id);

        return new LoginResponse(
            accessToken,
            refreshToken.Token,
            expires,
            user.Id,
            user.Username,
            user.DisplayName,
            user.Role.ToDbString());
    }

    public async Task<RefreshResponse> RefreshAsync(string refreshToken)
    {
        var stored = await _db.RefreshTokens
            .Include(t => t.User)
            .FirstOrDefaultAsync(t => t.Token == refreshToken);

        if (stored is null || stored.RevokedAt is not null || stored.ExpiresAt < DateTimeOffset.UtcNow)
            throw new ValidationException("Invalid or expired refresh token.", "INVALID_REFRESH_TOKEN");

        if (!stored.User.IsActive)
            throw new ValidationException("Account is deactivated.", "ACCOUNT_DEACTIVATED");

        stored.RevokedAt = DateTimeOffset.UtcNow;

        var newRefreshToken = await CreateRefreshTokenAsync(stored.UserId);

        var expires = DateTimeOffset.UtcNow.AddMinutes(_jwt.ExpirationMinutes);
        var accessToken = GenerateAccessToken(stored.User, expires);

        _db.ClinicalAuditLogs.Add(new ClinicalAuditLog
        {
            Id = Guid.NewGuid(),
            Action = AuditAction.TokenRefreshed,
            EntityType = "ClinicalUser",
            EntityId = stored.UserId,
            UserId = stored.UserId,
            UserDisplayName = stored.User.DisplayName,
            CreatedAt = DateTimeOffset.UtcNow
        });
        await _db.SaveChangesAsync();

        return new RefreshResponse(accessToken, newRefreshToken.Token, expires);
    }

    public async Task LogoutAsync(string refreshToken, Guid userId)
    {
        var stored = await _db.RefreshTokens
            .Include(t => t.User)
            .FirstOrDefaultAsync(t => t.Token == refreshToken && t.UserId == userId);

        if (stored is not null && stored.RevokedAt is null)
        {
            stored.RevokedAt = DateTimeOffset.UtcNow;

            _db.ClinicalAuditLogs.Add(new ClinicalAuditLog
            {
                Id = Guid.NewGuid(),
                Action = AuditAction.UserLogout,
                EntityType = "ClinicalUser",
                EntityId = userId,
                UserId = userId,
                UserDisplayName = stored.User.DisplayName,
                CreatedAt = DateTimeOffset.UtcNow
            });
            await _db.SaveChangesAsync();
        }
    }

    private async Task<RefreshToken> CreateRefreshTokenAsync(Guid userId)
    {
        var token = new RefreshToken
        {
            Id = Guid.NewGuid(),
            Token = GenerateOpaqueToken(),
            UserId = userId,
            ExpiresAt = DateTimeOffset.UtcNow.AddDays(_jwt.RefreshTokenExpirationDays),
            CreatedAt = DateTimeOffset.UtcNow
        };

        _db.RefreshTokens.Add(token);
        await _db.SaveChangesAsync();

        return token;
    }

    private static string GenerateOpaqueToken()
    {
        var bytes = RandomNumberGenerator.GetBytes(64);
        return Convert.ToBase64String(bytes);
    }

    private string GenerateAccessToken(ClinicalUser user, DateTimeOffset expires)
    {
        var claims = new[]
        {
            new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
            new Claim(ClaimTypes.Name, user.Username),
            new Claim("display_name", user.DisplayName),
            new Claim("clinical_role", user.Role.ToDbString()),
        };

        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwt.SigningKey));
        var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

        var token = new JwtSecurityToken(
            issuer: _jwt.Issuer,
            audience: _jwt.Audience,
            claims: claims,
            expires: expires.UtcDateTime,
            signingCredentials: creds);

        return new JwtSecurityTokenHandler().WriteToken(token);
    }
}