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

namespace SIGCM.Infrastructure.Repositories;

public class OperationRepository : IOperationRepository
{
    private readonly IDbConnectionFactory _connectionFactory;

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

    public async Task<IEnumerable<Operation>> GetAllAsync()
    {
        using var conn = _connectionFactory.CreateConnection();
        return await conn.QueryAsync<Operation>("SELECT * FROM Operations");
    }

    public async Task<Operation?> GetByIdAsync(int id)
    {
        using var conn = _connectionFactory.CreateConnection();
        return await conn.QueryFirstOrDefaultAsync<Operation>("SELECT * FROM Operations WHERE Id = @Id", new { Id = id });
    }

    public async Task<int> AddAsync(Operation operation)
    {
        using var conn = _connectionFactory.CreateConnection();
        var sql = @"
            INSERT INTO Operations (Name)
            VALUES (@Name);
            SELECT CAST(SCOPE_IDENTITY() as int);";
        return await conn.QuerySingleAsync<int>(sql, operation);
    }

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