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

namespace SIGCM.Infrastructure.Repositories;

public class AttributeDefinitionRepository : IAttributeDefinitionRepository
{
    private readonly IDbConnectionFactory _connectionFactory;

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

    public async Task<IEnumerable<AttributeDefinition>> GetByCategoryIdAsync(int categoryId)
    {
        using var conn = _connectionFactory.CreateConnection();
        return await conn.QueryAsync<AttributeDefinition>(
            "SELECT * FROM AttributeDefinitions WHERE CategoryId = @CategoryId", 
            new { CategoryId = categoryId });
    }

    public async Task<int> AddAsync(AttributeDefinition attribute)
    {
        using var conn = _connectionFactory.CreateConnection();
        var sql = @"
            INSERT INTO AttributeDefinitions (CategoryId, Name, DataType, Required)
            VALUES (@CategoryId, @Name, @DataType, @Required);
            SELECT CAST(SCOPE_IDENTITY() as int);";
        return await conn.QuerySingleAsync<int>(sql, attribute);
    }

    public async Task DeleteAsync(int id)
    {
        using var conn = _connectionFactory.CreateConnection();
        await conn.ExecuteAsync("DELETE FROM AttributeDefinitions WHERE Id = @Id", new { Id = id });
    }
}
