-- =====================================================
-- MIGRACIÓN 002: Unidades de Medida
-- Ejecutar sobre bases de datos existentes
-- =====================================================

-- 1. Crear tabla de unidades
CREATE TABLE IF NOT EXISTS `unidades` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `nombre` varchar(50) NOT NULL,
  `abreviatura` varchar(10) NOT NULL,
  `permite_decimales` tinyint(1) NOT NULL DEFAULT 1,
  `activa` tinyint(1) DEFAULT 1,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- 2. Insertar unidades por defecto (solo si la tabla está vacía)
INSERT IGNORE INTO `unidades` (`id`, `nombre`, `abreviatura`, `permite_decimales`) VALUES
(1, 'Unidad', 'und', 0),
(2, 'Kilogramo', 'kg', 1),
(3, 'Gramo', 'g', 1),
(4, 'Libra', 'lb', 1),
(5, 'Litro', 'lt', 1),
(6, 'Metro', 'm', 1);

-- 3. Agregar columna unidad_id a productos (default 1 = Unidad)
ALTER TABLE `productos` ADD COLUMN `unidad_id` int(11) NOT NULL DEFAULT 1 AFTER `categoria_id`;
ALTER TABLE `productos` ADD KEY `idx_unidad` (`unidad_id`);
ALTER TABLE `productos` ADD CONSTRAINT `fk_productos_unidad` FOREIGN KEY (`unidad_id`) REFERENCES `unidades` (`id`);

-- 4. Cambiar cantidad a decimal en stock_sucursal
ALTER TABLE `stock_sucursal` MODIFY COLUMN `cantidad` decimal(10,3) DEFAULT 0;
ALTER TABLE `stock_sucursal` MODIFY COLUMN `stock_minimo` decimal(10,3) DEFAULT 10;

-- 5. Cambiar cantidad a decimal en venta_items
ALTER TABLE `venta_items` MODIFY COLUMN `cantidad` decimal(10,3) NOT NULL;

-- 6. Cambiar cantidad a decimal en pedido_items
ALTER TABLE `pedido_items` MODIFY COLUMN `cantidad` decimal(10,3) NOT NULL;
