using Hc900Crawler.Infrastructure.Database;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace Hc900Crawler.Infrastructure.Kb;

/// <summary>
/// 앱 기동 시 kb_collections.is_active=TRUE 인 컬렉션에 대해 Qdrant 컬렉션을 idempotent 생성.
/// </summary>
public sealed class KbStartupService : IHostedService
{
    private readonly IServiceProvider _sp;
    private readonly KbQdrantClient _qdrant;
    private readonly ILogger<KbStartupService> _logger;

    public KbStartupService(IServiceProvider sp, KbQdrantClient qdrant, ILogger<KbStartupService> logger)
    {
        _sp = sp;
        _qdrant = qdrant;
        _logger = logger;
    }

    public async Task StartAsync(CancellationToken cancellationToken)
    {
        try
        {
            using var scope = _sp.CreateScope();
            var db = scope.ServiceProvider.GetRequiredService<Hc900DbContext>();
            var active = await db.KbCollections
                .Where(c => c.IsActive)
                .Select(c => c.QdrantName)
                .ToListAsync(cancellationToken);

            foreach (var name in active)
                await _qdrant.EnsureCollectionAsync(name, cancellationToken);

            _logger.LogInformation("[Kb] Qdrant 컬렉션 ensure 완료: {Count}건", active.Count);
        }
        catch (Exception ex)
        {
            _logger.LogWarning(ex, "[Kb] Qdrant 컬렉션 ensure 실패 — 추후 첫 사용 시 재시도 필요");
        }
    }

    public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
}
