-- Phase 4: Declarative Inventory Management Module
-- Creates module definition, forms, and action registrations
-- No custom JavaScript files needed - uses ModalBuilder, FormRenderer, DataLoader

-- ============================================================================
-- FORMS DEFINITIONS
-- ============================================================================

-- Form: Inventory Receiving
INSERT INTO forms (form_id, name, title, description, mapped_table, layout_type, is_active, org_id)
VALUES (
    gen_random_uuid(),
    'inventory_receive_form',
    'Receive Inventory',
    'Form for receiving inventory from suppliers or transfers',
    'inventory_receive',
    'grid',
    true,
    NULL -- Global form, works for all orgs
) ON CONFLICT (name) DO UPDATE SET
    title = EXCLUDED.title,
    description = EXCLUDED.description,
    mapped_table = EXCLUDED.mapped_table;

-- Get the form_id for inventory_receive_form
DO $$
DECLARE
    v_form_id UUID;
    v_section_id UUID;
BEGIN
    SELECT form_id INTO v_form_id FROM forms WHERE name = 'inventory_receive_form';
    
    -- Create form sections
    INSERT INTO form_sections (section_id, form_id, title, description, step, "order", layout)
    VALUES (
        gen_random_uuid(),
        v_form_id,
        'Delivery Information',
        'Basic information about the delivery',
        1,
        1,
        '{"type": "grid", "columns": "repeat(2, 1fr)", "gap": "1rem"}'::jsonb
    ) RETURNING section_id INTO v_section_id;
    
    -- Add form elements for delivery info section
    INSERT INTO form_elements (element_id, section_id, field_name, data_column, label, type, "order", required, options, validation, help_text)
    VALUES
        (gen_random_uuid(), v_section_id, 'vehicle_number', 'truck', 'Truck/Vehicle Number', 'text', 1, false, NULL, NULL, 'Vehicle delivering the goods'),
        (gen_random_uuid(), v_section_id, 'supply_date', 'date', 'Supply Date', 'date', 2, true, NULL, NULL, 'Date of delivery'),
        (gen_random_uuid(), v_section_id, 'vendor_id', 'vendor_id', 'Vendor', 'select-search', 3, false, 
            '{"options_table": "vendors", "options_label_column": "name", "options_value_column": "vendor_id"}'::jsonb, NULL, 'Select supplier'),
        (gen_random_uuid(), v_section_id, 'branch_id', 'branch_id', 'Receiving Location', 'select', 4, true,
            '{"options_table": "branches", "options_label_column": "name", "options_value_column": "branch_id"}'::jsonb, NULL, 'Warehouse or branch receiving goods'),
        (gen_random_uuid(), v_section_id, 'delivery_note_number', 'delivery_note_number', 'Delivery Note #', 'text', 5, false, NULL, NULL, 'Delivery note reference'),
        (gen_random_uuid(), v_section_id, 'lpo_number', 'lpo_number', 'LPO Number', 'text', 6, false, NULL, NULL, 'Local Purchase Order number'),
        (gen_random_uuid(), v_section_id, 'invoice_number', 'invoice_number', 'Invoice Number', 'text', 7, false, NULL, NULL, 'Supplier invoice number');
    
    -- Create products section with shopping cart
    INSERT INTO form_sections (section_id, form_id, title, description, step, "order", layout)
    VALUES (
        gen_random_uuid(),
        v_form_id,
        'Products',
        'Items being received',
        2,
        2,
        '{"type": "grid", "columns": "1fr", "gap": "1rem"}'::jsonb
    ) RETURNING section_id INTO v_section_id;
    
    -- Add shopping cart element
    INSERT INTO form_elements (element_id, section_id, field_name, data_column, label, type, "order", required, options)
    VALUES (
        gen_random_uuid(),
        v_section_id,
        'items',
        'items',
        'Products',
        'shopping-cart',
        1,
        true,
        '{
            "columns": [
                {"key": "product_id", "label": "Product", "type": "select-search", "required": true, "searchable": true},
                {"key": "quantity", "label": "Quantity", "type": "number", "required": true},
                {"key": "unit", "label": "Unit", "type": "select", "options": [
                    {"value": "PIECE", "label": "Piece"},
                    {"value": "CARTON", "label": "Carton"},
                    {"value": "PALLET", "label": "Pallet"}
                ]},
                {"key": "batch_number", "label": "Batch #", "type": "text"},
                {"key": "expiry_date", "label": "Expiry", "type": "date"}
            ],
            "productSource": "products",
            "productIdField": "product_id",
            "productLabelField": "name",
            "allowBarcode": true,
            "minRows": 1
        }'::jsonb
    );
END $$;

-- Form: Transfer/Dispatch
INSERT INTO forms (form_id, name, title, description, mapped_table, layout_type, is_active, org_id)
VALUES (
    gen_random_uuid(),
    'inventory_transfer_form',
    'Transfer Inventory',
    'Transfer inventory between locations',
    'dispatch_notes',
    'grid',
    true,
    NULL
) ON CONFLICT (name) DO UPDATE SET
    title = EXCLUDED.title,
    description = EXCLUDED.description;

DO $$
DECLARE
    v_form_id UUID;
    v_section_id UUID;
BEGIN
    SELECT form_id INTO v_form_id FROM forms WHERE name = 'inventory_transfer_form';
    
    -- Transfer info section
    INSERT INTO form_sections (section_id, form_id, title, step, "order", layout)
    VALUES (
        gen_random_uuid(),
        v_form_id,
        'Transfer Details',
        1,
        1,
        '{"type": "grid", "columns": "repeat(2, 1fr)", "gap": "1rem"}'::jsonb
    ) RETURNING section_id INTO v_section_id;
    
    INSERT INTO form_elements (element_id, section_id, field_name, data_column, label, type, "order", required, options, help_text)
    VALUES
        (gen_random_uuid(), v_section_id, 'from_branch_id', 'from_branch_id', 'From Location', 'select', 1, true,
            '{"options_table": "branches", "options_label_column": "name", "options_value_column": "branch_id"}'::jsonb, NULL),
        (gen_random_uuid(), v_section_id, 'to_branch_id', 'to_branch_id', 'To Location', 'select', 2, true,
            '{"options_table": "branches", "options_label_column": "name", "options_value_column": "branch_id"}'::jsonb, NULL),
        (gen_random_uuid(), v_section_id, 'vehicle_number', 'vehicle_number', 'Vehicle Number', 'text', 3, false, NULL, NULL),
        (gen_random_uuid(), v_section_id, 'driver_name', 'driver_name', 'Driver Name', 'text', 4, false, NULL, NULL);
    
    -- Products section
    INSERT INTO form_sections (section_id, form_id, title, step, "order", layout)
    VALUES (
        gen_random_uuid(),
        v_form_id,
        'Products to Transfer',
        2,
        2,
        '{"type": "grid", "columns": "1fr", "gap": "1rem"}'::jsonb
    ) RETURNING section_id INTO v_section_id;
    
    INSERT INTO form_elements (element_id, section_id, field_name, data_column, label, type, "order", required, options)
    VALUES
        (gen_random_uuid(), v_section_id, 'items', 'items', 'Products', 'shopping-cart', 1, true,
            '{
                "columns": [
                    {"key": "product_id", "label": "Product", "type": "select-search", "required": true},
                    {"key": "quantity", "label": "Quantity", "type": "number", "required": true},
                    {"key": "unit", "label": "Unit", "type": "select", "options": [
                        {"value": "PIECE", "label": "Piece"},
                        {"value": "CARTON", "label": "Carton"}
                    ]},
                    {"key": "batch_number", "label": "Batch #", "type": "text"},
                    {"key": "repack", "label": "Repack?", "type": "checkbox", "helpText": "Convert to pieces at destination"}
                ],
                "productSource": "products",
                "allowBarcode": true,
                "minRows": 1
            }'::jsonb),
        (gen_random_uuid(), v_section_id, 'notes', 'notes', 'Notes', 'textarea', 2, false, NULL);
END $$;

-- Form: Break Bulk
INSERT INTO forms (form_id, name, title, description, mapped_table, layout_type, is_active, org_id)
VALUES (
    gen_random_uuid(),
    'inventory_break_bulk_form',
    'Break Bulk Items',
    'Break down larger units into smaller units',
    'inventory_breaks',
    'grid',
    true,
    NULL
) ON CONFLICT (name) DO UPDATE SET
    title = EXCLUDED.title,
    description = EXCLUDED.description;

DO $$
DECLARE
    v_form_id UUID;
    v_section_id UUID;
BEGIN
    SELECT form_id INTO v_form_id FROM forms WHERE name = 'inventory_break_bulk_form';
    
    INSERT INTO form_sections (section_id, form_id, title, step, "order", layout)
    VALUES (
        gen_random_uuid(),
        v_form_id,
        'Break Bulk Details',
        1,
        1,
        '{"type": "grid", "columns": "repeat(2, 1fr)", "gap": "1rem"}'::jsonb
    ) RETURNING section_id INTO v_section_id;
    
    INSERT INTO form_elements (element_id, section_id, field_name, data_column, label, type, "order", required, options, help_text)
    VALUES
        (gen_random_uuid(), v_section_id, 'product_id', 'product_id', 'Product', 'select-search', 1, true,
            '{"options_table": "products", "options_label_column": "name", "options_value_column": "product_id"}'::jsonb, NULL),
        (gen_random_uuid(), v_section_id, 'branch_id', 'branch_id', 'Location', 'select', 2, true,
            '{"options_table": "branches", "options_label_column": "name", "options_value_column": "branch_id"}'::jsonb, NULL),
        (gen_random_uuid(), v_section_id, 'from_unit', 'from_unit', 'From Unit', 'select', 3, true,
            '{"options": [{"value": "PALLET", "label": "Pallet"}, {"value": "CARTON", "label": "Carton"}]}'::jsonb, NULL),
        (gen_random_uuid(), v_section_id, 'to_unit', 'to_unit', 'To Unit', 'select', 4, true,
            '{"options": [{"value": "CARTON", "label": "Carton"}, {"value": "PIECE", "label": "Piece"}]}'::jsonb, NULL),
        (gen_random_uuid(), v_section_id, 'quantity_to_break', 'quantity_to_break', 'Quantity to Break', 'number', 5, true, NULL, 'How many bulk units to break'),
        (gen_random_uuid(), v_section_id, 'batch_number', 'batch_number', 'Batch Number', 'text', 6, false, NULL, NULL),
        (gen_random_uuid(), v_section_id, 'notes', 'notes', 'Notes', 'textarea', 7, false, NULL, NULL);
END $$;

-- Form: Stock Adjustment
INSERT INTO forms (form_id, name, title, description, mapped_table, layout_type, is_active, org_id)
VALUES (
    gen_random_uuid(),
    'inventory_adjustment_form',
    'Adjust Stock',
    'Manual stock adjustment for corrections',
    'inventory_txn',
    'grid',
    true,
    NULL
) ON CONFLICT (name) DO UPDATE SET
    title = EXCLUDED.title,
    description = EXCLUDED.description;

DO $$
DECLARE
    v_form_id UUID;
    v_section_id UUID;
BEGIN
    SELECT form_id INTO v_form_id FROM forms WHERE name = 'inventory_adjustment_form';
    
    INSERT INTO form_sections (section_id, form_id, title, step, "order", layout)
    VALUES (
        gen_random_uuid(),
        v_form_id,
        'Adjustment Details',
        1,
        1,
        '{"type": "grid", "columns": "1fr", "gap": "1rem"}'::jsonb
    ) RETURNING section_id INTO v_section_id;
    
    INSERT INTO form_elements (element_id, section_id, field_name, data_column, label, type, "order", required, options, help_text)
    VALUES
        (gen_random_uuid(), v_section_id, 'product_name', 'product_name', 'Product', 'text', 1, false,
            '{"readonly": true}'::jsonb, NULL),
        (gen_random_uuid(), v_section_id, 'current_qty', 'current_qty', 'Current Quantity', 'number', 2, false,
            '{"readonly": true}'::jsonb, NULL),
        (gen_random_uuid(), v_section_id, 'adjustment_type', 'adjustment_type', 'Adjustment Type', 'select', 3, true,
            '{"options": [
                {"value": "add", "label": "Add Stock"},
                {"value": "remove", "label": "Remove Stock"},
                {"value": "set", "label": "Set Exact Quantity"}
            ]}'::jsonb, NULL),
        (gen_random_uuid(), v_section_id, 'quantity', 'quantity', 'Quantity', 'number', 4, true, NULL, 'For Set: exact quantity. For Add/Remove: amount to change'),
        (gen_random_uuid(), v_section_id, 'reason', 'reason', 'Reason', 'textarea', 5, true, NULL, 'Required: Explain the adjustment');
END $$;

-- Form: Warehouse/Branch
INSERT INTO forms (form_id, name, title, description, mapped_table, layout_type, is_active, org_id)
VALUES (
    gen_random_uuid(),
    'warehouse_form',
    'Warehouse Management',
    'Create or edit warehouse/branch locations',
    'branches',
    'grid',
    true,
    NULL
) ON CONFLICT (name) DO UPDATE SET
    title = EXCLUDED.title,
    description = EXCLUDED.description;

DO $$
DECLARE
    v_form_id UUID;
    v_section_id UUID;
BEGIN
    SELECT form_id INTO v_form_id FROM forms WHERE name = 'warehouse_form';
    
    INSERT INTO form_sections (section_id, form_id, title, step, "order", layout)
    VALUES (
        gen_random_uuid(),
        v_form_id,
        'Warehouse Information',
        1,
        1,
        '{"type": "grid", "columns": "repeat(2, 1fr)", "gap": "1rem"}'::jsonb
    ) RETURNING section_id INTO v_section_id;
    
    INSERT INTO form_elements (element_id, section_id, field_name, data_column, label, type, "order", required, options)
    VALUES
        (gen_random_uuid(), v_section_id, 'name', 'name', 'Warehouse Name', 'text', 1, true, NULL),
        (gen_random_uuid(), v_section_id, 'location', 'location', 'Location', 'text', 2, false, NULL),
        (gen_random_uuid(), v_section_id, 'branch_type', 'branch_type', 'Type', 'select', 3, false,
            '{"options": [
                {"value": "warehouse", "label": "Warehouse"},
                {"value": "retail", "label": "Retail Store"},
                {"value": "distribution", "label": "Distribution Center"}
            ]}'::jsonb),
        (gen_random_uuid(), v_section_id, 'is_active', 'is_active', 'Active', 'checkbox', 4, false, NULL);
END $$;

-- ============================================================================
-- MODULE DEFINITION
-- ============================================================================

INSERT INTO modules (
    module_id,
    name,
    title,
    description,
    icon,
    category,
    config,
    is_active,
    org_id,
    created_at,
    updated_at
) VALUES (
    gen_random_uuid(),
    'inventory_management',
    'Inventory Management',
    'Comprehensive inventory management with receiving, stock tracking, transfers, and bulk breaking',
    'fa-boxes',
    'operations',
    '{
        "layout": "tabs",
        "dataSources": {
            "inventory": {
                "endpoint": "/api/sync/inventory",
                "refresh": 30000,
                "fields": ["inventory_id", "product_batch_number_id", "branch_id", "current_qty", "unit_type"]
            },
            "inventory_txn": {
                "endpoint": "/api/sync/inventory_txn",
                "refresh": 60000
            },
            "inventory_receive": {
                "endpoint": "/api/sync/inventory_receive",
                "refresh": 60000
            },
            "dispatch_notes": {
                "endpoint": "/api/sync/dispatch_notes",
                "refresh": 60000
            },
            "products": {
                "endpoint": "/api/sync/products"
            },
            "branches": {
                "endpoint": "/api/sync/branches"
            },
            "vendors": {
                "endpoint": "/api/sync/vendors"
            }
        },
        "tabs": [
            {
                "id": "receive",
                "label": "Receive",
                "icon": "fa-truck-loading",
                "body": [
                    {
                        "type": "button",
                        "label": "Receive Inventory",
                        "icon": "fa-plus",
                        "class": "btn btn-primary mb-4",
                        "action": "inventory:receive"
                    },
                    {
                        "type": "table",
                        "options": {
                            "tableName": "inventory_receive",
                            "title": "Receiving History",
                            "columns": [
                                {"key": "date", "label": "Date", "sortable": true, "format": "date"},
                                {"key": "truck", "label": "Vehicle", "sortable": true},
                                {"key": "vendor_id", "label": "Vendor", "sortable": true},
                                {"key": "delivery_note_number", "label": "Delivery Note", "sortable": true},
                                {"key": "lpo_number", "label": "LPO", "sortable": true},
                                {"key": "invoice_number", "label": "Invoice", "sortable": true}
                            ],
                            "pagination": true,
                            "pageSize": 25,
                            "searchable": true,
                            "addButton": false,
                            "rowActions": [
                                {
                                    "label": "View Details",
                                    "icon": "fa-eye",
                                    "action": "inventory:viewReceipt"
                                }
                            ]
                        }
                    }
                ]
            },
            {
                "id": "stocks",
                "label": "Stocks",
                "icon": "fa-boxes",
                "lazy": true,
                "body": [
                    {
                        "type": "html",
                        "html": "<div class=\"flex gap-2 mb-4\"></div>",
                        "id": "stock-actions-toolbar"
                    },
                    {
                        "type": "button",
                        "label": "Transfer/Dispatch",
                        "icon": "fa-truck",
                        "class": "btn btn-primary",
                        "action": "inventory:dispatch",
                        "target": "#stock-actions-toolbar"
                    },
                    {
                        "type": "button",
                        "label": "Break Bulk",
                        "icon": "fa-box-open",
                        "class": "btn btn-secondary",
                        "action": "inventory:break",
                        "target": "#stock-actions-toolbar"
                    },
                    {
                        "type": "button",
                        "label": "Process Transactions",
                        "icon": "fa-sync",
                        "class": "btn btn-accent",
                        "action": "inventory:process",
                        "target": "#stock-actions-toolbar"
                    },
                    {
                        "type": "button",
                        "label": "Movement History",
                        "icon": "fa-history",
                        "class": "btn btn-info",
                        "action": "inventory:history",
                        "target": "#stock-actions-toolbar"
                    },
                    {
                        "type": "table",
                        "options": {
                            "tableName": "inventory",
                            "title": "Current Stock Levels",
                            "columns": [
                                {"key": "product_name", "label": "Product", "sortable": true},
                                {"key": "batch_number", "label": "Batch #", "sortable": true},
                                {"key": "warehouse", "label": "Location", "sortable": true},
                                {"key": "current_qty", "label": "Quantity", "sortable": true, "format": "number"},
                                {"key": "unit_type", "label": "Unit", "sortable": true},
                                {"key": "expiry_date", "label": "Expiry", "sortable": true, "format": "date"}
                            ],
                            "pagination": true,
                            "pageSize": 25,
                            "searchable": true,
                            "addButton": false,
                            "rowActions": [
                                {
                                    "label": "Adjust",
                                    "icon": "fa-edit",
                                    "action": "inventory:adjust",
                                    "confirm": false
                                },
                                {
                                    "label": "History",
                                    "icon": "fa-history",
                                    "action": "inventory:viewHistory",
                                    "confirm": false
                                }
                            ]
                        }
                    }
                ]
            },
            {
                "id": "warehouse",
                "label": "Warehouse",
                "icon": "fa-warehouse",
                "lazy": true,
                "body": [
                    {
                        "type": "button",
                        "label": "Add Warehouse",
                        "icon": "fa-plus",
                        "class": "btn btn-primary mb-4",
                        "action": "inventory:addWarehouse"
                    },
                    {
                        "type": "table",
                        "options": {
                            "tableName": "branches",
                            "title": "Warehouses & Branches",
                            "columns": [
                                {"key": "name", "label": "Name", "sortable": true},
                                {"key": "location", "label": "Location", "sortable": true},
                                {"key": "branch_type", "label": "Type", "sortable": true},
                                {"key": "is_active", "label": "Status", "format": "boolean"}
                            ],
                            "pagination": true,
                            "pageSize": 25,
                            "searchable": true,
                            "addButton": false,
                            "rowActions": [
                                {
                                    "label": "Edit",
                                    "icon": "fa-edit",
                                    "action": "inventory:editWarehouse"
                                }
                            ]
                        }
                    }
                ]
            }
        ]
    }'::jsonb,
    true,
    NULL,
    NOW(),
    NOW()
) ON CONFLICT (name) DO UPDATE SET
    title = EXCLUDED.title,
    description = EXCLUDED.description,
    icon = EXCLUDED.icon,
    category = EXCLUDED.category,
    config = EXCLUDED.config,
    updated_at = NOW();

-- ============================================================================
-- ACTION REGISTRY ENTRIES
-- ============================================================================

INSERT INTO ui_actions (action_id, name, label, icon, handler_type, handler_config, is_active, created_at)
VALUES
    (gen_random_uuid(), 'inventory:receive', 'Receive Inventory', 'fa-truck-loading', 'form', 
        '{"formName": "inventory_receive_form", "endpoint": "/api/inventory/receiveInventory", "method": "POST", "successMessage": "Inventory received successfully", "onSuccess": "refresh:inventory_receive,inventory_txn"}'::jsonb, true, NOW()),
    
    (gen_random_uuid(), 'inventory:dispatch', 'Transfer/Dispatch', 'fa-truck', 'form',
        '{"formName": "inventory_transfer_form", "endpoint": "/api/inventory/dispatch", "method": "POST", "successMessage": "Dispatch created successfully", "onSuccess": "refresh:dispatch_notes,inventory_txn"}'::jsonb, true, NOW()),
    
    (gen_random_uuid(), 'inventory:break', 'Break Bulk', 'fa-box-open', 'form',
        '{"formName": "inventory_break_bulk_form", "endpoint": "/api/inventory/break", "method": "POST", "successMessage": "Bulk items broken successfully", "onSuccess": "refresh:inventory_breaks,inventory_txn"}'::jsonb, true, NOW()),
    
    (gen_random_uuid(), 'inventory:adjust', 'Adjust Stock', 'fa-edit', 'form',
        '{"formName": "inventory_adjustment_form", "endpoint": "/api/inventory/adjust", "method": "POST", "successMessage": "Stock adjusted successfully", "onSuccess": "refresh:inventory_txn"}'::jsonb, true, NOW()),
    
    (gen_random_uuid(), 'inventory:process', 'Process Transactions', 'fa-sync', 'api',
        '{"endpoint": "/api/inventory/processTransactions", "method": "POST", "confirmMessage": "Process all pending inventory transactions?", "successMessage": "Transactions processed successfully", "onSuccess": "refresh:inventory,inventory_txn"}'::jsonb, true, NOW()),
    
    (gen_random_uuid(), 'inventory:history', 'Movement History', 'fa-history', 'modal',
        '{"title": "Inventory Movement History", "body": [{"type": "table", "options": {"tableName": "inventory_txn", "columns": [{"key": "created_at", "label": "Date", "format": "datetime"}, {"key": "product_name", "label": "Product"}, {"key": "change", "label": "Change", "format": "number"}, {"key": "unit_type", "label": "Unit"}, {"key": "reason", "label": "Reason"}, {"key": "reference_table", "label": "Source"}, {"key": "processed_at", "label": "Processed", "format": "datetime"}], "pagination": true, "pageSize": 50}}]}'::jsonb, true, NOW()),
    
    (gen_random_uuid(), 'inventory:viewHistory', 'View Product History', 'fa-history', 'modal',
        '{"title": "Product History", "body": [{"type": "table", "options": {"tableName": "inventory_txn", "filters": {"product_id": "{{record.product_id}}", "branch_id": "{{record.branch_id}}"}, "columns": [{"key": "created_at", "label": "Date", "format": "datetime"}, {"key": "change", "label": "Change", "format": "number"}, {"key": "unit_type", "label": "Unit"}, {"key": "reason", "label": "Reason"}, {"key": "processed_at", "label": "Processed", "format": "datetime"}], "pagination": true}}]}'::jsonb, true, NOW()),
    
    (gen_random_uuid(), 'inventory:addWarehouse', 'Add Warehouse', 'fa-plus', 'form',
        '{"formName": "warehouse_form", "successMessage": "Warehouse created successfully", "onSuccess": "refresh:branches"}'::jsonb, true, NOW()),
    
    (gen_random_uuid(), 'inventory:editWarehouse', 'Edit Warehouse', 'fa-edit', 'form',
        '{"formName": "warehouse_form", "populateRecord": true, "successMessage": "Warehouse updated successfully", "onSuccess": "refresh:branches"}'::jsonb, true, NOW()),
    
    (gen_random_uuid(), 'inventory:viewReceipt', 'View Receipt Details', 'fa-eye', 'modal',
        '{"title": "Receipt Details", "body": [{"type": "detail-view", "viewId": "inventory_receipt_detail"}]}'::jsonb, true, NOW())
ON CONFLICT (name) DO UPDATE SET
    label = EXCLUDED.label,
    icon = EXCLUDED.icon,
    handler_type = EXCLUDED.handler_type,
    handler_config = EXCLUDED.handler_config,
    updated_at = NOW();

-- ============================================================================
-- TENANT TABLES REGISTRY (for sync)
-- ============================================================================

INSERT INTO tenant_tables (table_name, sync_enabled, sync_endpoint, description, created_at)
VALUES
    ('inventory', true, '/api/sync/inventory', 'Current inventory stock levels', NOW()),
    ('inventory_txn', true, '/api/sync/inventory_txn', 'Inventory transaction log', NOW()),
    ('inventory_receive', true, '/api/sync/inventory_receive', 'Inventory receiving records', NOW()),
    ('inventory_breaks', true, '/api/sync/inventory_breaks', 'Bulk breaking records', NOW()),
    ('dispatch_notes', true, '/api/sync/dispatch_notes', 'Branch transfer dispatch notes', NOW()),
    ('dispatch_lines', true, '/api/sync/dispatch_lines', 'Dispatch note line items', NOW()),
    ('goods_receipts', true, '/api/sync/goods_receipts', 'Goods receipt records', NOW()),
    ('goods_receipt_lines', true, '/api/sync/goods_receipt_lines', 'Goods receipt line items', NOW()),
    ('product_batch_number', true, '/api/sync/product_batch_number', 'Product batch numbers', NOW())
ON CONFLICT (table_name) DO UPDATE SET
    sync_enabled = EXCLUDED.sync_enabled,
    sync_endpoint = EXCLUDED.sync_endpoint,
    description = EXCLUDED.description;

-- ============================================================================
-- PERMISSIONS
-- ============================================================================

-- Grant inventory management permissions to appropriate roles
-- This assumes you have a roles/permissions system in place

COMMENT ON TABLE modules IS 'Phase 4 declarative modules - no custom JS files needed';
COMMENT ON TABLE forms IS 'Declarative form definitions rendered by FormRenderer';
COMMENT ON TABLE ui_actions IS 'Action registry for module buttons and row actions';
