using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System.Text.Json;

namespace KiMailOrderAgent.Services;

public class WawiDbService
{
    private readonly IConfiguration _configuration;
    private readonly ILogger<WawiDbService> _logger;

    public WawiDbService(
        IConfiguration configuration,
        ILogger<WawiDbService> logger)
    {
        _configuration = configuration;
        _logger = logger;
    }

    public async Task SyncArticlesAsync()
    {
        var connectionString =
            _configuration.GetConnectionString("Wawi");

        await using var connection =
            new SqlConnection(connectionString);

        await connection.OpenAsync();

        const string sql = """
    SELECT
        a.cArtNr,
        b.cName
    FROM dbo.tArtikel a
    LEFT JOIN dbo.tArtikelBeschreibung b
        ON b.kArtikel = a.kArtikel
    WHERE a.cArtNr IS NOT NULL
      AND b.cName IS NOT NULL
    ORDER BY a.cArtNr
    """;

        var articles = new List<ArticleCatalogItem>();

        await using var cmd =
            new SqlCommand(sql, connection);

        await using var reader =
            await cmd.ExecuteReaderAsync();

        while (await reader.ReadAsync())
        {
            var article = new ArticleCatalogItem
            {
                ArticleNumber = reader["cArtNr"]?.ToString(),
                Name = reader["cName"]?.ToString(),
                Aliases = new List<string>()
            };

            articles.Add(article);
        }

        var json = JsonSerializer.Serialize(
            articles,
            new JsonSerializerOptions
            {
                WriteIndented = true
            });

        var outputPath = Path.Combine(
    AppContext.BaseDirectory,
    "articles.json");

        await File.WriteAllTextAsync(
            outputPath,
            json);

        _logger.LogInformation(
            "Artikel synchronisiert: {count}",
            articles.Count);
    }
}

public class ArticleCatalogItem
{
    public string? ArticleNumber { get; set; }

    public string? Name { get; set; }

    public List<string> Aliases { get; set; } = [];
}
