-- Migration pour la table Buy
CREATE TABLE IF NOT EXISTS Buy (
    id INT AUTO_INCREMENT PRIMARY KEY,
    supplier_id INT NOT NULL,
    inout_id INT,
    product_id INT NOT NULL,
    quantity INT NOT NULL,
    unit_price DECIMAL(10, 2) NOT NULL,
    packaging VARCHAR(50),
    discount DECIMAL(5, 2) DEFAULT 0.00,
    total_price DECIMAL(10, 2) GENERATED ALWAYS AS (quantity * unit_price * (1 - discount/100)) STORED,
    delivery_date DATE,
    status ENUM('pending', 'ordered', 'received', 'cancelled') DEFAULT 'pending',
    notes TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (supplier_id) REFERENCES Supplier(id),
    FOREIGN KEY (product_id) REFERENCES Product(id),
    FOREIGN KEY (inout_id) REFERENCES InOut(id) ON DELETE SET NULL,
    INDEX idx_buy_supplier (supplier_id),
    INDEX idx_buy_product (product_id),
    INDEX idx_buy_status (status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
