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

namespace SIGCM.Infrastructure.Repositories;

public class EditionClosureRepository
{
    private readonly IDbConnectionFactory _db;
    
    public EditionClosureRepository(IDbConnectionFactory db) => _db = db;

    // Cerrar una edición específica
    public async Task<int> CloseEditionAsync(EditionClosure closure)
    {
        using var conn = _db.CreateConnection();
        var sql = @"
            INSERT INTO EditionClosures (EditionDate, ClosureDateTime, ClosedByUserId, IsClosed, Notes)
            VALUES (@EditionDate, @ClosureDateTime, @ClosedByUserId, @IsClosed, @Notes);
            SELECT CAST(SCOPE_IDENTITY() as int);";
        
        return await conn.QuerySingleAsync<int>(sql, closure);
    }

    // Verificar si una edición está cerrada
    public async Task<bool> IsEditionClosedAsync(DateTime editionDate)
    {
        using var conn = _db.CreateConnection();
        var sql = "SELECT COUNT(1) FROM EditionClosures WHERE EditionDate = @Date AND IsClosed = 1";
        var count = await conn.ExecuteScalarAsync<int>(sql, new { Date = editionDate.Date });
        return count > 0;
    }

    // Reabrir una edición
    public async Task ReopenEditionAsync(DateTime editionDate)
    {
        using var conn = _db.CreateConnection();
        await conn.ExecuteAsync(
            "UPDATE EditionClosures SET IsClosed = 0 WHERE EditionDate = @Date", 
            new { Date = editionDate.Date });
    }

    // Obtener historial de cierres
    public async Task<IEnumerable<EditionClosure>> GetClosureHistoryAsync(int limit = 30)
    {
        using var conn = _db.CreateConnection();
        var sql = @"
            SELECT TOP (@Limit) ec.*, u.Username as ClosedByUsername
            FROM EditionClosures ec
            JOIN Users u ON ec.ClosedByUserId = u.Id
            ORDER BY ec.EditionDate DESC";
        
        return await conn.QueryAsync<EditionClosure>(sql, new { Limit = limit });
    }

    // Obtener el cierre de una fecha específica
    public async Task<EditionClosure?> GetClosureByDateAsync(DateTime editionDate)
    {
        using var conn = _db.CreateConnection();
        var sql = @"
            SELECT ec.*, u.Username as ClosedByUsername
            FROM EditionClosures ec
            JOIN Users u ON ec.ClosedByUserId = u.Id
            WHERE ec.EditionDate = @Date";
        
        return await conn.QuerySingleOrDefaultAsync<EditionClosure>(sql, new { Date = editionDate.Date });
    }
}
