using Dapper;
using TaxBaik.Domain.Entities;
using TaxBaik.Domain.Interfaces;

namespace TaxBaik.Infrastructure.Repositories;

public class SiteSettingRepository(IDbConnectionFactory connectionFactory) : BaseRepository(connectionFactory), ISiteSettingRepository
{
    public async Task<IReadOnlyDictionary<string, string>> GetAllAsync(CancellationToken cancellationToken = default)
    {
        using var conn = Conn();
        var rows = await conn.QueryAsync<SiteSetting>(
            "SELECT key, value, updated_at AS UpdatedAt FROM site_settings ORDER BY key");
        return rows.ToDictionary(x => x.Key, x => x.Value);
    }

    public async Task UpsertAsync(IEnumerable<SiteSetting> settings, CancellationToken cancellationToken = default)
    {
        using var conn = Conn();
        foreach (var setting in settings)
        {
            await conn.ExecuteAsync(
                @"INSERT INTO site_settings (key, value, updated_at)
                  VALUES (@Key, @Value, NOW())
                  ON CONFLICT (key)
                  DO UPDATE SET value = EXCLUDED.value, updated_at = NOW()",
                setting);
        }
    }
}
