using MongoDB.Driver;
using Nalu.Web.Data.Models;

namespace Nalu.Web.Data.Repositories;

public class ApiKeyRepository(MongoDbContext db)
{
    public async Task<ApiKey?> FindAsync(string key, CancellationToken ct = default)
    {
        if (!db.IsConnected) return null;

        return await db.ApiKeys
            .Find(k => k.Key == key && k.IsActive)
            .FirstOrDefaultAsync(ct);
    }

    public async Task TouchAsync(string key, CancellationToken ct = default)
    {
        if (!db.IsConnected) return;

        await db.ApiKeys.UpdateOneAsync(
            k => k.Key == key,
            Builders<ApiKey>.Update.Set(k => k.LastUsedAt, DateTime.UtcNow),
            cancellationToken: ct);
    }

    public async Task InsertAsync(ApiKey apiKey, CancellationToken ct = default)
    {
        await db.ApiKeys.InsertOneAsync(apiKey, cancellationToken: ct);
    }

    public async Task<List<ApiKey>> GetByUserAsync(string userId, CancellationToken ct = default)
    {
        if (!db.IsConnected) return [];

        return await db.ApiKeys
            .Find(k => k.UserId == userId && k.IsActive)
            .ToListAsync(ct);
    }

    public async Task RevokeAsync(string key, CancellationToken ct = default)
    {
        await db.ApiKeys.UpdateOneAsync(
            k => k.Key == key,
            Builders<ApiKey>.Update.Set(k => k.IsActive, false),
            cancellationToken: ct);
    }
}
