-- ============================================================
-- SCRIPT SQL: SISTEMA DE INVENTARIOS
-- Base de datos: eventos_georgina
-- Descripción: Sistema de control de inventario para productos
--              vendidos por libras (carnes frías)
-- ============================================================

-- Tabla: inventarios
-- Descripción: Almacena el stock actual de cada producto
-- ============================================================
CREATE TABLE IF NOT EXISTS `inventarios` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `producto_id` bigint(20) NOT NULL,
  `stock_actual` decimal(10,2) NOT NULL DEFAULT 0.00 COMMENT 'Stock actual en libras o unidades',
  `stock_minimo` decimal(10,2) DEFAULT 0.00 COMMENT 'Alerta de stock mínimo',
  `stock_maximo` decimal(10,2) DEFAULT NULL COMMENT 'Stock máximo permitido',
  `unidad_medida` varchar(20) NOT NULL DEFAULT 'libra' COMMENT 'libra, unidad, porcion',
  `activo` tinyint(1) NOT NULL DEFAULT 1 COMMENT '1=activo, 0=inactivo',
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `inventarios_producto_id_unique` (`producto_id`),
  KEY `inventarios_producto_id_index` (`producto_id`),
  KEY `inventarios_activo_index` (`activo`),
  CONSTRAINT `inventarios_producto_id_FK` FOREIGN KEY (`producto_id`)
    REFERENCES `productos` (`id`)
    ON DELETE CASCADE
    ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
COMMENT='Control de inventario de productos';


-- ============================================================
-- Tabla: movimientos_inventario
-- Descripción: Registra todos los movimientos de entrada/salida
-- ============================================================
CREATE TABLE IF NOT EXISTS `movimientos_inventario` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `producto_id` bigint(20) NOT NULL,
  `tipo` enum('entrada','salida','ajuste','devolucion') NOT NULL COMMENT 'entrada=compra, salida=venta, ajuste=corrección, devolucion=cliente',
  `cantidad` decimal(10,2) NOT NULL COMMENT 'Cantidad del movimiento (positivo o negativo)',
  `stock_anterior` decimal(10,2) NOT NULL COMMENT 'Stock antes del movimiento',
  `stock_nuevo` decimal(10,2) NOT NULL COMMENT 'Stock después del movimiento',
  `referencia_tipo` varchar(50) DEFAULT NULL COMMENT 'Tipo de referencia: pedido, compra, ajuste',
  `referencia_id` bigint(20) DEFAULT NULL COMMENT 'ID de la referencia (pedido_id, compra_id, etc)',
  `motivo` varchar(255) DEFAULT NULL COMMENT 'Descripción o motivo del movimiento',
  `user_id` bigint(20) NOT NULL COMMENT 'Usuario que realizó el movimiento',
  `fecha_movimiento` datetime NOT NULL COMMENT 'Fecha y hora del movimiento',
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `movimientos_inventario_producto_id_index` (`producto_id`),
  KEY `movimientos_inventario_user_id_index` (`user_id`),
  KEY `movimientos_inventario_tipo_index` (`tipo`),
  KEY `movimientos_inventario_fecha_index` (`fecha_movimiento`),
  KEY `movimientos_inventario_referencia_index` (`referencia_tipo`, `referencia_id`),
  CONSTRAINT `movimientos_inventario_producto_id_FK` FOREIGN KEY (`producto_id`)
    REFERENCES `productos` (`id`)
    ON DELETE CASCADE
    ON UPDATE CASCADE,
  CONSTRAINT `movimientos_inventario_user_id_FK` FOREIGN KEY (`user_id`)
    REFERENCES `users` (`id`)
    ON DELETE RESTRICT
    ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
COMMENT='Historial de movimientos de inventario';


-- ============================================================
-- Tabla: alertas_inventario
-- Descripción: Registra alertas cuando el stock está bajo
-- ============================================================
CREATE TABLE IF NOT EXISTS `alertas_inventario` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `producto_id` bigint(20) NOT NULL,
  `tipo_alerta` enum('stock_bajo','stock_critico','stock_agotado') NOT NULL,
  `stock_actual` decimal(10,2) NOT NULL,
  `stock_minimo` decimal(10,2) NOT NULL,
  `fecha_alerta` datetime NOT NULL,
  `resuelta` tinyint(1) NOT NULL DEFAULT 0 COMMENT '1=resuelta, 0=pendiente',
  `fecha_resolucion` datetime DEFAULT NULL,
  `user_resolucion` bigint(20) DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `alertas_inventario_producto_id_index` (`producto_id`),
  KEY `alertas_inventario_resuelta_index` (`resuelta`),
  KEY `alertas_inventario_tipo_index` (`tipo_alerta`),
  KEY `alertas_inventario_fecha_index` (`fecha_alerta`),
  CONSTRAINT `alertas_inventario_producto_id_FK` FOREIGN KEY (`producto_id`)
    REFERENCES `productos` (`id`)
    ON DELETE CASCADE
    ON UPDATE CASCADE,
  CONSTRAINT `alertas_inventario_user_resolucion_FK` FOREIGN KEY (`user_resolucion`)
    REFERENCES `users` (`id`)
    ON DELETE SET NULL
    ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
COMMENT='Alertas de stock bajo para productos';


-- ============================================================
-- ÍNDICES ADICIONALES PARA OPTIMIZACIÓN
-- ============================================================

-- Índice compuesto para búsquedas de movimientos por producto y fecha
CREATE INDEX `movimientos_producto_fecha_idx`
  ON `movimientos_inventario` (`producto_id`, `fecha_movimiento` DESC);

-- Índice para búsquedas de alertas pendientes
CREATE INDEX `alertas_pendientes_idx`
  ON `alertas_inventario` (`resuelta`, `fecha_alerta` DESC);


-- ============================================================
-- DATOS INICIALES (OPCIONAL)
-- ============================================================

-- Ejemplo: Insertar inventarios para productos de carnes
-- Descomentar y ajustar según tus productos existentes
/*
INSERT INTO `inventarios` (`producto_id`, `stock_actual`, `stock_minimo`, `stock_maximo`, `unidad_medida`, `activo`)
VALUES
  (1, 50.00, 10.00, 100.00, 'libra', 1),  -- PAVO
  (2, 45.00, 10.00, 100.00, 'libra', 1),  -- SOBREBARRIGA
  (3, 60.00, 15.00, 120.00, 'libra', 1),  -- POLLO RELLENO
  (4, 40.00, 10.00, 100.00, 'libra', 1);  -- PERNIL
*/


-- ============================================================
-- TRIGGER: Actualizar stock automáticamente al insertar movimiento
-- ============================================================
DELIMITER $$

CREATE TRIGGER `actualizar_stock_despues_movimiento`
AFTER INSERT ON `movimientos_inventario`
FOR EACH ROW
BEGIN
    -- Actualizar el stock en la tabla inventarios
    UPDATE `inventarios`
    SET `stock_actual` = NEW.stock_nuevo,
        `updated_at` = NOW()
    WHERE `producto_id` = NEW.producto_id;

    -- Verificar si se debe crear una alerta de stock bajo
    IF NEW.stock_nuevo <= (SELECT stock_minimo FROM inventarios WHERE producto_id = NEW.producto_id) THEN
        INSERT INTO `alertas_inventario`
        (`producto_id`, `tipo_alerta`, `stock_actual`, `stock_minimo`, `fecha_alerta`, `resuelta`)
        SELECT
            NEW.producto_id,
            CASE
                WHEN NEW.stock_nuevo = 0 THEN 'stock_agotado'
                WHEN NEW.stock_nuevo <= (stock_minimo * 0.5) THEN 'stock_critico'
                ELSE 'stock_bajo'
            END,
            NEW.stock_nuevo,
            stock_minimo,
            NOW(),
            0
        FROM inventarios
        WHERE producto_id = NEW.producto_id
        -- Solo insertar si no existe una alerta pendiente reciente (últimas 24 horas)
        AND NOT EXISTS (
            SELECT 1 FROM alertas_inventario
            WHERE producto_id = NEW.producto_id
            AND resuelta = 0
            AND fecha_alerta >= DATE_SUB(NOW(), INTERVAL 24 HOUR)
        );
    END IF;
END$$

DELIMITER ;


-- ============================================================
-- CONSULTAS ÚTILES PARA VERIFICACIÓN
-- ============================================================

-- Ver todos los inventarios con sus productos
-- SELECT i.*, p.nombre, p.unidad_medida
-- FROM inventarios i
-- INNER JOIN productos p ON i.producto_id = p.id
-- ORDER BY i.stock_actual ASC;

-- Ver movimientos recientes
-- SELECT m.*, p.nombre, u.name as usuario
-- FROM movimientos_inventario m
-- INNER JOIN productos p ON m.producto_id = p.id
-- INNER JOIN users u ON m.user_id = u.id
-- ORDER BY m.fecha_movimiento DESC
-- LIMIT 50;

-- Ver alertas pendientes
-- SELECT a.*, p.nombre
-- FROM alertas_inventario a
-- INNER JOIN productos p ON a.producto_id = p.id
-- WHERE a.resuelta = 0
-- ORDER BY a.fecha_alerta DESC;

-- ============================================================
-- FIN DEL SCRIPT
-- ============================================================
