using AiLogia.Bot.Services;
using Microsoft.Extensions.Configuration;
using Npgsql;

namespace AiLogia.Bot.Data;

public class RecomendationsModel
{
    public string DbValue { get; set; } = String.Empty;

    public bool HasData => !String.IsNullOrEmpty(DbValue);
}

public interface IRecommendationsRepository
{
    Task<RecomendationsModel> GetRecommendations(long telegramUserId);
}

public class RecommendationsRepository : IRecommendationsRepository
{
    private readonly ISystemLogService _log;
    private readonly string _connectionString;

    public RecommendationsRepository(IConfiguration config, ISystemLogService log)
    {
        _log = log;
        _connectionString = config.GetConnectionString("Postgres") ??
                            throw new InvalidOperationException("Missing Postgres connection string");
    }

    public async Task<RecomendationsModel> GetRecommendations(long telegramUserId)
    {
        var recommendations = new RecomendationsModel();

        try
        {
            await using var conn = new NpgsqlConnection(_connectionString);
            await conn.OpenAsync();

            var cmd = new NpgsqlCommand("select get_recommendations(@user_id)", conn);

            cmd.Parameters.AddWithValue("user_id", NpgsqlTypes.NpgsqlDbType.Bigint, telegramUserId);

            recommendations.DbValue = ((await cmd.ExecuteScalarAsync()) as string) ?? String.Empty;
        }
        catch (Exception ex)
        {
            await _log.ExceptionAsync(ex, new { telegramUserId });
        }

        return recommendations;
    }
}
