-- =============================================================================
-- inventory_business_scope.sql - Inventory records follow the selected business.
-- Products (inv_products) had no business at all; this adds business_id (nullable - existing products stay
-- shared and keep showing under every business until someone assigns one), exposes it as businessId in
-- vw_products, and the API now filters products, warehouses, stock items, digital and physical assets by the
-- business chosen in the top bar. Idempotent. Must run after products_sp_views.sql (it redefines vw_products).
-- =============================================================================

SET @col_exists = (SELECT COUNT(*) FROM information_schema.COLUMNS
                   WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'inv_products' AND COLUMN_NAME = 'business_id');
SET @sql = IF(@col_exists = 0, 'ALTER TABLE `inv_products` ADD COLUMN `business_id` INT NULL AFTER `tenant_id`', 'SELECT 1');
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;

SET @idx_exists = (SELECT COUNT(*) FROM information_schema.STATISTICS
                   WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'inv_products' AND INDEX_NAME = 'idx_inv_products_business');
SET @sql = IF(@idx_exists = 0, 'ALTER TABLE `inv_products` ADD INDEX `idx_inv_products_business` (`tenant_id`, `business_id`, `is_deleted`)', 'SELECT 1');
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;

CREATE OR REPLACE VIEW vw_products AS
SELECT
    p.id            AS id,
    p.id            AS productId,
    p.tenant_id     AS tenant_id,
    p.business_id   AS businessId,
    p.name          AS name,
    p.sku           AS sku,
    p.category      AS category,
    p.unit_price    AS unitPrice,
    p.cost_price    AS costPrice,
    p.currency      AS currency,
    p.stock_qty     AS stockQty,
    p.reorder_level AS reorderLevel,
    p.unit          AS unit,
    p.status        AS status,
    p.created_at    AS createdAt,
    p.updated_at    AS updatedAt
FROM inv_products p
WHERE p.is_deleted = 0;
