CREATE TABLE `order_items` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `order_id` int(10) unsigned NOT NULL,
  `product_id` int(10) unsigned NOT NULL,
  `quantity` int(10) unsigned NOT NULL,
  `returned_quantity` int(11) NOT NULL DEFAULT 0,
  `unit_price` bigint(20) unsigned NOT NULL,
  `total_price` bigint(20) unsigned NOT NULL,
  `has_used_battery` tinyint(1) NOT NULL DEFAULT 0,
  `used_battery_amperage` int(10) unsigned DEFAULT NULL,
  `used_battery_amperage_2` int(10) unsigned DEFAULT NULL,
  `used_battery_rate` int(10) unsigned DEFAULT NULL COMMENT 'Rate per amp at order time',
  `used_battery_credit` bigint(20) unsigned NOT NULL DEFAULT 0,
  `used_battery_received` tinyint(1) NOT NULL DEFAULT 0,
  `used_battery_received_at` datetime DEFAULT NULL,
  `has_installation` tinyint(1) NOT NULL DEFAULT 0,
  `installation_fee` bigint(20) unsigned NOT NULL DEFAULT 0,
  `warranty_months` int(11) NOT NULL,
  `warranty_start_date` date DEFAULT NULL,
  `warranty_end_date` date DEFAULT NULL,
  `warranty_code` varchar(50) DEFAULT NULL,
  `product_snapshot` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL CHECK (json_valid(`product_snapshot`)),
  `created_at` datetime NOT NULL DEFAULT current_timestamp(),
  PRIMARY KEY (`id`),
  KEY `idx_order` (`order_id`),
  KEY `idx_product` (`product_id`),
  KEY `idx_warranty` (`warranty_code`),
  CONSTRAINT `fk_order_items_order` FOREIGN KEY (`order_id`) REFERENCES `orders` (`id`) ON DELETE CASCADE,
  CONSTRAINT `fk_order_items_product` FOREIGN KEY (`product_id`) REFERENCES `products` (`id`),
  CONSTRAINT `chk_oi_quantity_positive` CHECK (`quantity` > 0),
  CONSTRAINT `chk_oi_unit_price_positive` CHECK (`unit_price` >= 0),
  CONSTRAINT `chk_oi_total_price_positive` CHECK (`total_price` >= 0)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
