-- ============================================================================
-- Phase 6: TaxCore Enhancement - Data Seeding
-- ============================================================================
-- This file seeds the TaxCore workflows and modules after database schema
-- is created. Run this after TAFDB.pgsql is loaded.
--
-- Components:
--   1. TaxCore Workflows (6 workflows)
--   2. TaxCore Modules (4 modules)
--
-- Created: October 17, 2025
-- Status: Production Ready
-- ============================================================================

-- Prerequisites check
DO $$
BEGIN
    -- Check if workflows table exists
    IF NOT EXISTS (SELECT FROM pg_tables WHERE tablename = 'workflows') THEN
        RAISE EXCEPTION 'workflows table does not exist. Run TAFDB.pgsql first.';
    END IF;
    
    -- Check if modules table exists
    IF NOT EXISTS (SELECT FROM pg_tables WHERE tablename = 'modules') THEN
        RAISE EXCEPTION 'modules table does not exist. Run TAFDB.pgsql first.';
    END IF;
    
    -- Check if taxcore tables exist
    IF NOT EXISTS (SELECT FROM pg_tables WHERE tablename = 'taxcore_submissions') THEN
        RAISE EXCEPTION 'taxcore_submissions table does not exist. Run TAFDB.pgsql first.';
    END IF;
END $$;

-- ============================================================================
-- SECTION 1: TAXCORE WORKFLOWS
-- ============================================================================

-- Delete existing TaxCore workflows (for idempotency)
DELETE FROM workflows WHERE name IN (
    'Auto-submit Invoice to TaxCore',
    'Auto-submit Sales Receipt to TaxCore',
    'TaxCore Submission Failed - Notify Admin',
    'TaxCore Retry Exceeded - Escalate',
    'TaxCore Submission Success - Update Source',
    'Process TaxCore Retry Queue'
);

-- Workflow 1: Auto-submit Invoice to TaxCore
INSERT INTO workflows (name, trigger_event, definition, is_active)
VALUES (
    'Auto-submit Invoice to TaxCore',
    'invoice:status:finalized',
    '{
        "description": "Automatically submit invoices to TaxCore when finalized",
        "priority": 5,
        "max_retries": 3,
        "retry_delay": 300,
        "steps": [
            {
                "step": 1,
                "action": "query",
                "name": "validate_org_config",
                "query": "SELECT org_id, api_base_url, org_tin, certificate_file FROM taxcore_configurations WHERE org_id = ${record.org_id} AND is_active = true",
                "required": true
            },
            {
                "step": 2,
                "action": "query",
                "name": "check_idempotency",
                "query": "SELECT submission_id FROM taxcore_submissions WHERE reference_table = ''invoices'' AND reference_id = ${record.invoice_id} AND status = ''success''",
                "required": false
            },
            {
                "step": 3,
                "action": "conditional",
                "name": "skip_if_exists",
                "condition": "step2.result.length > 0",
                "if_true": {"action": "return", "message": "Already submitted"},
                "if_false": {"action": "continue"}
            },
            {
                "step": 4,
                "action": "transform",
                "name": "transform_invoice",
                "source": "${record}",
                "mapping": {
                    "invoiceNumber": "${record.invoice_number}",
                    "invoiceDate": "${record.invoice_date}",
                    "customerName": "${record.customer_name}",
                    "customerTIN": "${record.customer_tin}",
                    "totalAmount": "${record.total_amount}",
                    "taxAmount": "${record.tax_amount}",
                    "lineItems": "${record.line_items}"
                }
            },
            {
                "step": 5,
                "action": "http_post",
                "name": "submit_to_taxcore",
                "url": "http://taxcore-service:3001/submit",
                "headers": {
                    "Content-Type": "application/json"
                },
                "body": "${step4.output}",
                "required": true
            },
            {
                "step": 6,
                "action": "update",
                "name": "update_invoice",
                "query": "UPDATE invoices SET taxcore_invoice_number = ${step5.response.invoiceNumber}, taxcore_submission_id = ${step5.response.submissionId} WHERE invoice_id = ${record.invoice_id}",
                "required": false
            },
            {
                "step": 7,
                "action": "notify",
                "name": "notify_success",
                "channel": "websocket",
                "event": "taxcore:submission:success",
                "data": {
                    "invoice_id": "${record.invoice_id}",
                    "taxcore_invoice_number": "${step5.response.invoiceNumber}"
                }
            }
        ]
    }'::json,
    true
);

-- Workflow 2: Auto-submit Sales Receipt to TaxCore
INSERT INTO workflows (name, trigger_event, definition, is_active)
VALUES (
    'Auto-submit Sales Receipt to TaxCore',
    'sales_receipt:created',
    '{
        "description": "Automatically submit POS sales receipts to TaxCore in real-time",
        "priority": 10,
        "max_retries": 3,
        "retry_delay": 60,
        "steps": [
            {
                "step": 1,
                "action": "query",
                "name": "validate_org_config",
                "query": "SELECT org_id, api_base_url, org_tin, certificate_file FROM taxcore_configurations WHERE org_id = ${record.org_id} AND is_active = true AND auto_submit_receipts = true",
                "required": true
            },
            {
                "step": 2,
                "action": "transform",
                "name": "transform_receipt",
                "source": "${record}",
                "mapping": {
                    "receiptNumber": "${record.receipt_number}",
                    "saleDate": "${record.sale_date}",
                    "customerName": "${record.customer_name || ''Anonymous''}",
                    "totalAmount": "${record.total_amount}",
                    "taxAmount": "${record.tax_amount}",
                    "lineItems": "${record.line_items}"
                }
            },
            {
                "step": 3,
                "action": "http_post",
                "name": "submit_to_taxcore",
                "url": "http://taxcore-service:3001/submit",
                "headers": {
                    "Content-Type": "application/json"
                },
                "body": "${step2.output}",
                "required": true
            },
            {
                "step": 4,
                "action": "update",
                "name": "update_receipt",
                "query": "UPDATE sales_receipts SET taxcore_receipt_number = ${step3.response.receiptNumber}, taxcore_submission_id = ${step3.response.submissionId} WHERE receipt_id = ${record.receipt_id}",
                "required": false
            },
            {
                "step": 5,
                "action": "trigger_event",
                "name": "trigger_success",
                "event": "taxcore:submission:success",
                "data": {
                    "reference_table": "sales_receipts",
                    "reference_id": "${record.receipt_id}",
                    "submission_id": "${step3.response.submissionId}"
                }
            }
        ]
    }'::json,
    true
);

-- Workflow 3: TaxCore Submission Failed - Notify Admin
INSERT INTO workflows (name, trigger_event, definition, is_active)
VALUES (
    'TaxCore Submission Failed - Notify Admin',
    'taxcore:submission:failed',
    '{
        "description": "Notify administrators when TaxCore submission fails after multiple attempts",
        "priority": 8,
        "condition": "status = ''failed'' AND attempts >= 3",
        "steps": [
            {
                "step": 1,
                "action": "query",
                "name": "get_submission_details",
                "query": "SELECT s.*, c.org_tin FROM taxcore_submissions s LEFT JOIN taxcore_configurations c ON s.org_id = c.org_id WHERE s.submission_id = ${record.submission_id}",
                "required": true
            },
            {
                "step": 2,
                "action": "query",
                "name": "get_admin_emails",
                "query": "SELECT email FROM users WHERE role = ''admin'' AND org_id = ${step1.result[0].org_id} AND is_active = true",
                "required": true
            },
            {
                "step": 3,
                "action": "email",
                "name": "send_alert_email",
                "to": "${step2.result.map(u => u.email).join('','')}", 
                "subject": "TaxCore Submission Failed - ${step1.result[0].submission_type} #${step1.result[0].invoice_number}",
                "template": "taxcore_failure_alert",
                "data": "${step1.result[0]}"
            },
            {
                "step": 4,
                "action": "insert",
                "name": "create_notification",
                "query": "INSERT INTO notifications (user_id, title, message, type, data) SELECT user_id, ''TaxCore Submission Failed'', ''Failed to submit ${step1.result[0].submission_type} after 3 attempts'', ''error'', ${step1.result[0]}::jsonb FROM users WHERE role = ''admin'' AND org_id = ${step1.result[0].org_id}",
                "required": false
            },
            {
                "step": 5,
                "action": "notify",
                "name": "websocket_alert",
                "channel": "websocket",
                "event": "taxcore:alert:failed",
                "room": "org:${step1.result[0].org_id}",
                "data": "${step1.result[0]}"
            }
        ]
    }'::json,
    true
);

-- Workflow 4: TaxCore Retry Exceeded - Escalate
INSERT INTO workflows (name, trigger_event, definition, is_active)
VALUES (
    'TaxCore Retry Exceeded - Escalate',
    'taxcore:retry:exceeded',
    '{
        "description": "Escalate to support when max retry attempts are exceeded",
        "priority": 10,
        "steps": [
            {
                "step": 1,
                "action": "query",
                "name": "get_submission",
                "query": "SELECT * FROM taxcore_submissions WHERE submission_id = ${record.submission_id}",
                "required": true
            },
            {
                "step": 2,
                "action": "update",
                "name": "mark_failed",
                "query": "UPDATE taxcore_submissions SET status = ''failed'', error_message = ''Max retry attempts exceeded'' WHERE submission_id = ${record.submission_id}",
                "required": true
            },
            {
                "step": 3,
                "action": "insert",
                "name": "create_support_ticket",
                "query": "INSERT INTO support_tickets (org_id, title, description, priority, status, category) VALUES (${step1.result[0].org_id}, ''TaxCore Submission Failed'', ''Submission ${record.submission_id} failed after maximum retry attempts'', ''high'', ''open'', ''taxcore'')",
                "required": false
            },
            {
                "step": 4,
                "action": "email",
                "name": "email_support",
                "to": "support@taxcore.example.com",
                "subject": "TaxCore Max Retries Exceeded - ${step1.result[0].org_tin}",
                "template": "taxcore_escalation",
                "data": "${step1.result[0]}"
            },
            {
                "step": 5,
                "action": "trigger_event",
                "name": "trigger_failure_event",
                "event": "taxcore:submission:failed",
                "data": "${record}"
            }
        ]
    }'::json,
    true
);

-- Workflow 5: TaxCore Submission Success - Update Source
INSERT INTO workflows (name, trigger_event, definition, is_active)
VALUES (
    'TaxCore Submission Success - Update Source',
    'taxcore:submission:success',
    '{
        "description": "Update source document when TaxCore submission succeeds",
        "priority": 3,
        "steps": [
            {
                "step": 1,
                "action": "query",
                "name": "get_submission",
                "query": "SELECT * FROM taxcore_submissions WHERE submission_id = ${record.submission_id}",
                "required": true
            },
            {
                "step": 2,
                "action": "conditional",
                "name": "update_by_type",
                "condition": "step1.result[0].reference_table == ''invoices''",
                "if_true": {
                    "action": "update",
                    "query": "UPDATE invoices SET taxcore_invoice_number = ${step1.result[0].taxcore_invoice_number}, taxcore_verified_at = NOW() WHERE invoice_id = ${step1.result[0].reference_id}"
                },
                "if_false": {
                    "action": "update",
                    "query": "UPDATE sales_receipts SET taxcore_receipt_number = ${step1.result[0].taxcore_invoice_number}, taxcore_verified_at = NOW() WHERE receipt_id = ${step1.result[0].reference_id}"
                }
            },
            {
                "step": 3,
                "action": "notify",
                "name": "notify_user",
                "channel": "websocket",
                "event": "document:taxcore:verified",
                "room": "org:${step1.result[0].org_id}",
                "data": {
                    "reference_table": "${step1.result[0].reference_table}",
                    "reference_id": "${step1.result[0].reference_id}",
                    "taxcore_number": "${step1.result[0].taxcore_invoice_number}"
                }
            }
        ]
    }'::json,
    true
);

-- Workflow 6: Process TaxCore Retry Queue (Scheduled)
INSERT INTO workflows (name, trigger_event, definition, is_active)
VALUES (
    'Process TaxCore Retry Queue',
    'schedule:cron',
    '{
        "description": "Process TaxCore retry queue every 5 minutes (handled by PHP cron job)",
        "schedule": "*/5 * * * *",
        "priority": 5,
        "steps": [
            {
                "step": 1,
                "action": "query",
                "name": "get_queue_items",
                "query": "SELECT q.*, s.* FROM taxcore_queue q JOIN taxcore_submissions s ON q.submission_id = s.submission_id WHERE q.status = ''queued'' AND q.retry_count < q.max_retries AND q.next_retry_at <= NOW() ORDER BY q.priority DESC, q.next_retry_at ASC LIMIT 50",
                "required": false
            },
            {
                "step": 2,
                "action": "foreach",
                "name": "process_each_item",
                "array": "${step1.result}",
                "steps": [
                    {
                        "step": 1,
                        "action": "http_post",
                        "name": "retry_submission",
                        "url": "http://taxcore-service:3001/submit",
                        "headers": {"Content-Type": "application/json"},
                        "body": "${item.request_payload}",
                        "handle_error": "continue"
                    },
                    {
                        "step": 2,
                        "action": "conditional",
                        "name": "update_based_on_result",
                        "condition": "step1.status == 200",
                        "if_true": {
                            "action": "update",
                            "query": "DELETE FROM taxcore_queue WHERE queue_id = ${item.queue_id}; UPDATE taxcore_submissions SET status = ''success'', taxcore_invoice_number = ${step1.response.invoiceNumber} WHERE submission_id = ${item.submission_id}"
                        },
                        "if_false": {
                            "action": "update",
                            "query": "UPDATE taxcore_queue SET retry_count = retry_count + 1, next_retry_at = NOW() + INTERVAL ''${item.base_delay_minutes * POWER(item.backoff_multiplier, item.retry_count + 1)} minutes'', last_error = ${step1.error} WHERE queue_id = ${item.queue_id}"
                        }
                    }
                ]
            },
            {
                "step": 3,
                "action": "notify",
                "name": "log_completion",
                "channel": "log",
                "message": "Processed ${step1.result.length} queue items"
            }
        ]
    }'::json,
    true
);

-- ============================================================================
-- SECTION 2: TAXCORE MODULES
-- ============================================================================

-- Delete existing TaxCore modules (for idempotency)
DELETE FROM modules WHERE name IN (
    'TaxCoreSubmissions',
    'TaxCoreDashboard',
    'TaxCoreConfiguration',
    'TaxCoreFailedAlert'
);

-- Module 1: TaxCoreSubmissions (List Module)
INSERT INTO modules (
    module_id,
    name,
    icon,
    description,
    config
) VALUES (
    uuid_generate_v7(),
    'TaxCoreSubmissions',
    'fa-file-invoice',
    'TaxCore submission history and monitoring',
    '{
        "type": "list",
        "dataSource": "/api/taxcore/submission-history/{org_id}",
        "refreshInterval": 30000,
        "pagination": true,
        "pageSize": 50,
        "exportable": true,
        "filters": [
            {"key": "status", "label": "Status", "type": "select", "options": [
                {"value": "success", "label": "Success"},
                {"value": "failed", "label": "Failed"},
                {"value": "pending", "label": "Pending"},
                {"value": "retrying", "label": "Retrying"}
            ]},
            {"key": "submission_type", "label": "Type", "type": "select", "options": [
                {"value": "invoice", "label": "Invoice"},
                {"value": "sales_receipt", "label": "Sales Receipt"}
            ]},
            {"key": "date_from", "label": "From Date", "type": "date"},
            {"key": "date_to", "label": "To Date", "type": "date"}
        ],
        "columns": [
            {"key": "submission_id", "label": "Submission ID", "type": "uuid", "sortable": true, "copyable": true},
            {"key": "status", "label": "Status", "type": "badge", "sortable": true, "badges": {
                "success": {"class": "badge-success", "icon": "fa-check-circle"},
                "failed": {"class": "badge-error", "icon": "fa-times-circle"},
                "pending": {"class": "badge-warning", "icon": "fa-clock"},
                "retrying": {"class": "badge-info", "icon": "fa-sync-alt"}
            }},
            {"key": "submission_type", "label": "Type", "type": "text", "sortable": true},
            {"key": "source_id", "label": "Source ID", "type": "uuid", "copyable": true},
            {"key": "taxcore_invoice_number", "label": "TaxCore Invoice #", "type": "text", "sortable": true, "copyable": true},
            {"key": "total_amount", "label": "Amount", "type": "currency", "sortable": true},
            {"key": "attempts", "label": "Attempts", "type": "number", "sortable": true},
            {"key": "created_at", "label": "Created", "type": "datetime", "sortable": true, "defaultSort": "desc"}
        ],
        "rowActions": [
            {"label": "View Details", "icon": "fa-eye", "action": "taxcore:view", "openModal": true},
            {"label": "Retry Submission", "icon": "fa-redo", "action": "taxcore:retry", "condition": "status == \"failed\" || status == \"retrying\"", "confirm": "Retry this submission?"},
            {"label": "View PDF", "icon": "fa-file-pdf", "action": "taxcore:pdf", "condition": "status == \"success\"", "target": "_blank"},
            {"label": "Copy TaxCore URL", "icon": "fa-link", "action": "taxcore:copy-url", "condition": "status == \"success\""}
        ],
        "bulkActions": [
            {"label": "Retry Selected", "icon": "fa-redo", "action": "taxcore:bulk-retry", "confirm": "Retry {count} selected submission(s)?"},
            {"label": "Export to CSV", "icon": "fa-file-csv", "action": "export:csv"}
        ]
    }'::jsonb
);

-- Module 2: TaxCoreDashboard (Dashboard Module)
INSERT INTO modules (
    module_id,
    name,
    icon,
    description,
    config
) VALUES (
    uuid_generate_v7(),
    'TaxCoreDashboard',
    'fa-chart-line',
    'TaxCore real-time monitoring dashboard',
    '{
        "type": "dashboard",
        "refreshInterval": 30000,
        "layout": "grid",
        "widgets": [
            {
                "id": "stats_overview",
                "type": "stats",
                "title": "Submission Overview",
                "col": 1,
                "row": 1,
                "width": 4,
                "height": 1,
                "dataSource": "/api/taxcore/stats/{org_id}",
                "stats": [
                    {"key": "total", "label": "Total Submissions", "icon": "fa-file-invoice", "color": "primary"},
                    {"key": "successful", "label": "Successful", "icon": "fa-check-circle", "color": "success"},
                    {"key": "failed", "label": "Failed", "icon": "fa-times-circle", "color": "error"},
                    {"key": "pending", "label": "Pending", "icon": "fa-clock", "color": "warning"}
                ]
            },
            {
                "id": "success_rate",
                "type": "gauge",
                "title": "Success Rate",
                "col": 1,
                "row": 2,
                "width": 2,
                "height": 1,
                "dataSource": "/api/taxcore/stats/{org_id}",
                "valueKey": "success_rate",
                "min": 0,
                "max": 100,
                "unit": "%",
                "ranges": [
                    {"min": 0, "max": 70, "color": "error", "label": "Critical"},
                    {"min": 70, "max": 90, "color": "warning", "label": "Warning"},
                    {"min": 90, "max": 100, "color": "success", "label": "Healthy"}
                ]
            },
            {
                "id": "total_amount",
                "type": "metric",
                "title": "Total Amount Submitted",
                "col": 3,
                "row": 2,
                "width": 2,
                "height": 1,
                "dataSource": "/api/taxcore/stats/{org_id}",
                "valueKey": "total_amount",
                "format": "currency",
                "trend": true,
                "trendKey": "amount_trend"
            },
            {
                "id": "recent_submissions",
                "type": "list",
                "title": "Recent Submissions",
                "col": 1,
                "row": 3,
                "width": 4,
                "height": 2,
                "dataSource": "/api/taxcore/submission-history/{org_id}",
                "limit": 10,
                "columns": [
                    {"key": "status", "label": "Status", "type": "badge"},
                    {"key": "submission_type", "label": "Type"},
                    {"key": "taxcore_invoice_number", "label": "Invoice #"},
                    {"key": "total_amount", "label": "Amount", "type": "currency"},
                    {"key": "created_at", "label": "Time", "type": "datetime"}
                ],
                "actions": [{"label": "View All", "link": "/taxcore/submissions"}]
            }
        ]
    }'::jsonb
);

-- Module 3: TaxCoreConfiguration (Form Module)
INSERT INTO modules (
    module_id,
    name,
    icon,
    description,
    config
) VALUES (
    uuid_generate_v7(),
    'TaxCoreConfiguration',
    'fa-cog',
    'TaxCore API configuration and settings',
    '{
        "type": "form",
        "dataSource": "/api/taxcore/config/{org_id}",
        "submitEndpoint": "/api/taxcore/config/{org_id}",
        "method": "POST",
        "sections": [
            {
                "title": "API Configuration",
                "fields": [
                    {"name": "api_base_url", "label": "API Base URL", "type": "url", "required": true, "placeholder": "https://api.taxcore.gov", "help": "TaxCore API endpoint URL"},
                    {"name": "org_tin", "label": "Organization TIN", "type": "text", "required": true, "pattern": "^[0-9]{9}$", "placeholder": "123456789", "help": "9-digit Tax Identification Number"},
                    {"name": "api_version", "label": "API Version", "type": "select", "required": true, "options": [
                        {"value": "v1", "label": "Version 1.0"},
                        {"value": "v2", "label": "Version 2.0 (Recommended)"}
                    ], "default": "v2"}
                ]
            },
            {
                "title": "Certificate Configuration",
                "fields": [
                    {"name": "certificate_file", "label": "Certificate File (.p12)", "type": "file", "required": true, "accept": ".p12,.pfx", "help": "Upload your TaxCore digital certificate"},
                    {"name": "certificate_password", "label": "Certificate Password", "type": "password", "required": true, "help": "Password for the certificate file"},
                    {"name": "certificate_expiry", "label": "Certificate Expiry Date", "type": "date", "readonly": true, "help": "Automatically detected from certificate"}
                ]
            },
            {
                "title": "Submission Settings",
                "fields": [
                    {"name": "auto_submit_invoices", "label": "Auto-submit Invoices", "type": "checkbox", "default": true, "help": "Automatically submit invoices when finalized"},
                    {"name": "auto_submit_receipts", "label": "Auto-submit Sales Receipts", "type": "checkbox", "default": true, "help": "Automatically submit POS receipts"},
                    {"name": "retry_max_attempts", "label": "Max Retry Attempts", "type": "number", "required": true, "min": 1, "max": 10, "default": 3, "help": "Maximum number of retry attempts for failed submissions"},
                    {"name": "retry_base_delay", "label": "Base Retry Delay (seconds)", "type": "number", "required": true, "min": 60, "max": 3600, "default": 300, "help": "Initial delay before retrying"}
                ]
            },
            {
                "title": "Environment",
                "fields": [
                    {"name": "is_sandbox", "label": "Sandbox Mode", "type": "checkbox", "default": false, "help": "Use sandbox environment for testing"},
                    {"name": "is_active", "label": "TaxCore Integration Active", "type": "checkbox", "default": true, "help": "Enable or disable TaxCore integration"}
                ]
            }
        ],
        "actions": [
            {"label": "Test Connection", "action": "taxcore:test-connection", "icon": "fa-plug", "type": "button", "class": "btn-secondary"},
            {"label": "Save Configuration", "type": "submit", "icon": "fa-save", "class": "btn-primary"}
        ],
        "validation": {
            "showErrors": "onSubmit",
            "scrollToError": true
        }
    }'::jsonb
);

-- Module 4: TaxCoreFailedAlert (Alert Module)
INSERT INTO modules (
    module_id,
    name,
    icon,
    description,
    config
) VALUES (
    uuid_generate_v7(),
    'TaxCoreFailedAlert',
    'fa-exclamation-triangle',
    'Alert for failed TaxCore submissions',
    '{
        "type": "alert",
        "severity": "error",
        "dataSource": "/api/taxcore/failed-count/{org_id}",
        "refreshInterval": 10000,
        "showWhen": "count > 0",
        "template": "{count} TaxCore submission(s) failed and require attention",
        "actions": [
            {"label": "View Failed Submissions", "link": "/taxcore/submissions?status=failed", "icon": "fa-eye"},
            {"label": "Retry All Failed", "action": "taxcore:retry-all-failed", "icon": "fa-redo", "confirm": "Retry all failed submissions?"}
        ],
        "sound": {
            "enabled": true,
            "playWhen": "count > previous_count",
            "soundFile": "/sounds/alert.mp3"
        },
        "dismissible": true,
        "persistent": true
    }'::jsonb
);

-- ============================================================================
-- VERIFICATION
-- ============================================================================

-- Verify workflows
DO $$
DECLARE
    workflow_count INTEGER;
BEGIN
    SELECT COUNT(*) INTO workflow_count FROM workflows WHERE name LIKE '%TaxCore%';
    IF workflow_count <> 6 THEN
        RAISE WARNING 'Expected 6 TaxCore workflows, found %', workflow_count;
    ELSE
        RAISE NOTICE '✅ Successfully inserted 6 TaxCore workflows';
    END IF;
END $$;

-- Verify modules
DO $$
DECLARE
    module_count INTEGER;
BEGIN
    SELECT COUNT(*) INTO module_count FROM modules WHERE name LIKE '%TaxCore%';
    IF module_count <> 4 THEN
        RAISE WARNING 'Expected 4 TaxCore modules, found %', module_count;
    ELSE
        RAISE NOTICE '✅ Successfully inserted 4 TaxCore modules';
    END IF;
END $$;

-- Display results
SELECT 
    'Workflows' as component,
    COUNT(*) as count,
    string_agg(name, ', ' ORDER BY name) as names
FROM workflows 
WHERE name LIKE '%TaxCore%'
UNION ALL
SELECT 
    'Modules' as component,
    COUNT(*) as count,
    string_agg(name, ', ' ORDER BY name) as names
FROM modules 
WHERE name LIKE '%TaxCore%';

-- ============================================================================
-- END OF PHASE 6 DATA SEEDING
-- ============================================================================
