-- ========================================
-- CORRECCIÓN: Movimientos de caja negativos incorrectos
-- ========================================
-- Fecha: 2026-01-31
-- Problema: Los movimientos de venta (income) tienen montos negativos
--           porque se restó incorrectamente el cambio (change)
-- 
-- Causa: CashRegisterService restaba el cambio del montant, pero el montant
--        ya representa el monto neto que debe quedar en caja
--
-- Solución: Recalcular los amounts usando solo el montant original
-- ========================================

-- PASO 1: Crear respaldo antes de corregir
CREATE TABLE IF NOT EXISTS cash_register_movements_backup_20260131 AS 
SELECT * FROM cash_register_movements 
WHERE amount < 0 AND movement_type = 'income' AND source_type = 'sale_payment';

SELECT CONCAT('✓ Respaldo creado con ', COUNT(*), ' registros') as status
FROM cash_register_movements_backup_20260131;

-- PASO 2: Ver estadísticas ANTES de la corrección
SELECT 
    '=== ANTES DE LA CORRECCIÓN ===' as info,
    COUNT(*) as total_negativos,
    MIN(amount) as menor_monto,
    MAX(amount) as mayor_monto_negativo,
    SUM(amount) as suma_total_negativa
FROM cash_register_movements
WHERE amount < 0 
  AND movement_type = 'income'
  AND source_type = 'sale_payment';

-- PASO 3: CORRECCIÓN - Actualizar los montos negativos
-- El monto correcto es el montant del PaymentSale (sin restar el change)
UPDATE cash_register_movements crm
INNER JOIN payment_sales ps ON crm.source_id = ps.id AND crm.source_type = 'sale_payment'
SET crm.amount = ps.montant
WHERE crm.amount < 0
  AND crm.movement_type = 'income'
  AND crm.source_type = 'sale_payment';

-- PASO 4: Verificar la corrección
SELECT 
    '=== DESPUÉS DE LA CORRECCIÓN ===' as info,
    COUNT(*) as total_negativos_restantes,
    COUNT(CASE WHEN crm.amount > 0 THEN 1 END) as total_corregidos,
    MIN(crm.amount) as menor_monto,
    MAX(crm.amount) as mayor_monto,
    SUM(crm.amount) as suma_total
FROM cash_register_movements crm
WHERE crm.source_type = 'sale_payment'
  AND crm.movement_type = 'income';

-- PASO 5: Ver algunos ejemplos de registros corregidos
SELECT 
    'Ejemplos de registros corregidos' as info,
    crm.id,
    crm.description,
    backup.amount as amount_anterior,
    crm.amount as amount_corregido,
    (crm.amount - backup.amount) as diferencia,
    ps.montant,
    ps.change as cambio,
    crm.created_at
FROM cash_register_movements crm
INNER JOIN cash_register_movements_backup_20260131 backup ON crm.id = backup.id
INNER JOIN payment_sales ps ON crm.source_id = ps.id
ORDER BY crm.created_at DESC
LIMIT 10;

-- PASO 6: Verificar que NO quedan movimientos negativos de tipo income/sale_payment
SELECT 
    CASE 
        WHEN COUNT(*) = 0 THEN '✓ ÉXITO: No quedan movimientos negativos de ventas'
        ELSE CONCAT('⚠️ ADVERTENCIA: Aún quedan ', COUNT(*), ' movimientos negativos')
    END as resultado_final
FROM cash_register_movements
WHERE amount < 0 
  AND movement_type = 'income'
  AND source_type = 'sale_payment';

-- ========================================
-- NOTAS:
-- - Este script solo corrige movimientos de VENTAS (sale_payment)
-- - Los movimientos de tipo 'refund' y 'expense' DEBEN ser negativos
-- - El respaldo se guarda en: cash_register_movements_backup_20260131
-- ========================================
