using Dapper;
using SIGCM.Domain.Entities;
using SIGCM.Domain.Interfaces;
using SIGCM.Infrastructure.Data;

namespace SIGCM.Infrastructure.Repositories;

public class ImageRepository : IImageRepository
{
    private readonly IDbConnectionFactory _connectionFactory;

    public ImageRepository(IDbConnectionFactory connectionFactory)
    {
        _connectionFactory = connectionFactory;
    }

    public async Task AddAsync(ListingImage image)
    {
        using var conn = _connectionFactory.CreateConnection();
        var sql = @"
            INSERT INTO ListingImages (ListingId, Url, IsMainInfo, DisplayOrder)
            VALUES (@ListingId, @Url, @IsMainInfo, @DisplayOrder)";
        await conn.ExecuteAsync(sql, image);
    }

    // Obtiene una imagen por su ID
    public async Task<ListingImage?> GetByIdAsync(int id)
    {
        using var conn = _connectionFactory.CreateConnection();
        return await conn.QuerySingleOrDefaultAsync<ListingImage>(
            "SELECT * FROM ListingImages WHERE Id = @Id", 
            new { Id = id });
    }

    // Obtiene las imágenes de un aviso ordenadas
    public async Task<IEnumerable<ListingImage>> GetByListingIdAsync(int listingId)
    {
        using var conn = _connectionFactory.CreateConnection();
        return await conn.QueryAsync<ListingImage>(
            "SELECT * FROM ListingImages WHERE ListingId = @ListingId ORDER BY DisplayOrder", 
            new { ListingId = listingId });
    }

    // Elimina el registro de una imagen de la base de datos
    public async Task DeleteAsync(int id)
    {
        using var conn = _connectionFactory.CreateConnection();
        await conn.ExecuteAsync("DELETE FROM ListingImages WHERE Id = @Id", new { Id = id });
    }
}
