-- ============================================================
-- Migration: BOM Consumption Ledger
-- Adds the bom_consumption base table (Level 2 Execution).
-- The live DB already has this table (with batch_no/lot_no added
-- by migration_production_enhancements.sql); this makes the table
-- reproducible on a fresh install. Idempotent (IF NOT EXISTS).
-- Mirrors §13 of database/production_schema.sql.
-- ============================================================

CREATE TABLE IF NOT EXISTS `bom_consumption` (
  `id` int unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int unsigned NOT NULL DEFAULT 1,
  `production_order_id` int unsigned NOT NULL,
  `process_order_id` int unsigned DEFAULT NULL,
  `operation_id` int unsigned DEFAULT NULL COMMENT 'production_order_operations.id',
  `confirmation_id` int unsigned DEFAULT NULL,
  `material_id` int unsigned NOT NULL COMMENT 'production_order_materials.id',
  `item_id` int unsigned DEFAULT NULL COMMENT 'master_items.id',
  `item_name` varchar(255) NOT NULL,
  `bom_qty` decimal(14,4) NOT NULL DEFAULT 0,
  `output_qty` int unsigned NOT NULL DEFAULT 0,
  `consumed_qty` decimal(14,4) NOT NULL DEFAULT 0,
  `wastage_qty` decimal(14,4) NOT NULL DEFAULT 0,
  `uom` varchar(20) DEFAULT 'PCS',
  `batch_no` varchar(50) DEFAULT NULL,
  `lot_no` varchar(50) DEFAULT NULL,
  `rate` decimal(12,2) DEFAULT 0,
  `total_cost` decimal(14,2) DEFAULT 0,
  `consumed_at` datetime DEFAULT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `company_id` (`company_id`),
  KEY `production_order_id` (`production_order_id`),
  KEY `operation_id` (`operation_id`),
  KEY `material_id` (`material_id`),
  KEY `confirmation_id` (`confirmation_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
