using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
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 token = GenerateToken(user, expires);

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

    private string GenerateToken(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);
    }
}