using Nalu.Web.Data.Models;
using Nalu.Web.Data.Repositories;
using Nalu.Web.Infrastructure;

namespace Nalu.Web.Services;

/// <summary>
/// Validates API keys. Checks MongoDB first, falls back to config for test/bootstrap keys.
/// </summary>
public class AuthService(ApiKeyRepository apiKeyRepo, IConfiguration config)
{
    private readonly List<ApiKeyConfig> _configKeys =
        config.GetSection("ApiKeys").Get<List<ApiKeyConfig>>() ?? [];

    public async Task<(string Plan, string Owner)?> ValidateAsync(string? key, CancellationToken ct = default)
    {
        if (string.IsNullOrWhiteSpace(key)) return null;

        var dbKey = await apiKeyRepo.FindAsync(key, ct);
        if (dbKey is not null) return (dbKey.Plan, dbKey.Owner);

        var cfgKey = _configKeys.FirstOrDefault(k => k.Key == key);
        return cfgKey is not null ? (cfgKey.Plan, cfgKey.Owner) : null;
    }

    public string? GetPlan(string key)
    {
        var cfgKey = _configKeys.FirstOrDefault(k => k.Key == key);
        return cfgKey?.Plan;
    }
}
