-- ============================================================================
-- Phase 6: TaxCore Enhancement - Module Definitions
-- ============================================================================
-- Created: October 17, 2025
-- Purpose: Create declarative modules for TaxCore submission management
-- Dependencies: modules table (Phase 4), ModuleLoader, DataLoader, ModalBuilder
-- ============================================================================

-- ============================================================================
-- Module 1: TaxCore Submissions List
-- ============================================================================
-- Purpose: Main list view for all TaxCore submissions with filtering and actions
-- ============================================================================

INSERT INTO modules (
    module_id,
    name,
    title,
    icon,
    category,
    description,
    config,
    is_active,
    created_at,
    updated_at
) VALUES (
    uuid_generate_v7(),
    'TaxCoreSubmissions',
    'TaxCore Submissions',
    'fa-file-invoice',
    'finance',
    'View and manage TaxCore fiscal receipt submissions',
    '{
        "type": "list",
        "dataSource": {
            "url": "/api/taxcore/submission-history/{org_id}",
            "method": "GET",
            "params": {
                "limit": 50,
                "offset": 0
            },
            "pagination": true,
            "refresh": 30000
        },
        "filters": [
            {
                "key": "status",
                "label": "Status",
                "type": "select",
                "options": [
                    {"value": "", "label": "All"},
                    {"value": "success", "label": "Success"},
                    {"value": "failed", "label": "Failed"},
                    {"value": "pending", "label": "Pending"},
                    {"value": "retrying", "label": "Retrying"}
                ],
                "default": ""
            },
            {
                "key": "submission_type",
                "label": "Type",
                "type": "select",
                "options": [
                    {"value": "", "label": "All Types"},
                    {"value": "Training", "label": "Training"},
                    {"value": "Normal", "label": "Normal"},
                    {"value": "Proforma", "label": "Proforma"},
                    {"value": "Copy", "label": "Copy"}
                ],
                "default": ""
            },
            {
                "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",
                "width": "200px",
                "truncate": true,
                "copyable": true
            },
            {
                "key": "status",
                "label": "Status",
                "type": "badge",
                "width": "100px",
                "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-redo"}
                }
            },
            {
                "key": "reference_table",
                "label": "Source",
                "type": "text",
                "width": "120px",
                "transform": {
                    "sales_receipts": "Sales Receipt",
                    "invoices": "Invoice"
                }
            },
            {
                "key": "invoice_number",
                "label": "Invoice #",
                "type": "text",
                "width": "150px"
            },
            {
                "key": "taxcore_invoice_number",
                "label": "TaxCore #",
                "type": "text",
                "width": "180px",
                "copyable": true
            },
            {
                "key": "total_amount",
                "label": "Amount",
                "type": "currency",
                "width": "120px",
                "align": "right"
            },
            {
                "key": "attempts",
                "label": "Attempts",
                "type": "number",
                "width": "80px",
                "align": "center"
            },
            {
                "key": "created_at",
                "label": "Submitted",
                "type": "datetime",
                "width": "180px"
            }
        ],
        "rowActions": [
            {
                "label": "View Details",
                "icon": "fa-eye",
                "action": "taxcore:view",
                "color": "primary"
            },
            {
                "label": "Retry",
                "icon": "fa-redo",
                "action": "taxcore:retry",
                "color": "warning",
                "condition": "status == \"failed\"",
                "confirm": "Retry this submission?"
            },
            {
                "label": "View Receipt",
                "icon": "fa-file-pdf",
                "action": "taxcore:pdf",
                "color": "success",
                "condition": "status == \"success\" && taxcore_invoice_number != null",
                "target": "_blank"
            },
            {
                "label": "Copy Verification URL",
                "icon": "fa-link",
                "action": "taxcore:copy-url",
                "color": "info",
                "condition": "taxcore_verification_url != null"
            }
        ],
        "bulkActions": [
            {
                "label": "Retry Selected",
                "icon": "fa-redo",
                "action": "taxcore:bulk-retry",
                "confirm": "Retry {count} selected submission(s)?"
            },
            {
                "label": "Export to CSV",
                "icon": "fa-download",
                "action": "export:csv"
            }
        ],
        "emptyState": {
            "icon": "fa-file-invoice",
            "title": "No TaxCore Submissions",
            "message": "No submissions found matching your criteria.",
            "action": {
                "label": "Clear Filters",
                "handler": "clearFilters"
            }
        }
    }'::jsonb,
    true,
    NOW(),
    NOW()
) ON CONFLICT (name) DO UPDATE SET
    config = EXCLUDED.config,
    updated_at = NOW();

-- ============================================================================
-- Module 2: TaxCore Dashboard
-- ============================================================================
-- Purpose: Dashboard with statistics widgets and real-time monitoring
-- ============================================================================

INSERT INTO modules (
    module_id,
    name,
    title,
    icon,
    category,
    description,
    config,
    is_active,
    created_at,
    updated_at
) VALUES (
    uuid_generate_v7(),
    'TaxCoreDashboard',
    'TaxCore Dashboard',
    'fa-chart-line',
    'finance',
    'Real-time TaxCore submission statistics and monitoring',
    '{
        "type": "dashboard",
        "layout": "grid",
        "refreshInterval": 30000,
        "widgets": [
            {
                "id": "stats_overview",
                "type": "stats",
                "title": "Submission Overview",
                "size": "full",
                "dataSource": "/api/taxcore/dashboard-stats/{org_id}",
                "stats": [
                    {
                        "key": "total_submissions",
                        "label": "Total Submissions",
                        "icon": "fa-file-alt",
                        "color": "primary"
                    },
                    {
                        "key": "successful",
                        "label": "Successful",
                        "icon": "fa-check-circle",
                        "color": "success",
                        "percentage": "total_submissions"
                    },
                    {
                        "key": "failed",
                        "label": "Failed",
                        "icon": "fa-times-circle",
                        "color": "error",
                        "percentage": "total_submissions",
                        "alert": {
                            "threshold": 5,
                            "message": "High failure rate"
                        }
                    },
                    {
                        "key": "pending",
                        "label": "Pending",
                        "icon": "fa-clock",
                        "color": "warning"
                    }
                ]
            },
            {
                "id": "success_rate",
                "type": "gauge",
                "title": "Success Rate",
                "size": "half",
                "dataSource": "/api/taxcore/dashboard-stats/{org_id}",
                "calculate": "(successful / total_submissions) * 100",
                "format": "percentage",
                "ranges": [
                    {"min": 0, "max": 70, "color": "error", "label": "Poor"},
                    {"min": 70, "max": 90, "color": "warning", "label": "Fair"},
                    {"min": 90, "max": 100, "color": "success", "label": "Excellent"}
                ]
            },
            {
                "id": "total_amount",
                "type": "metric",
                "title": "Total Amount Submitted",
                "size": "half",
                "dataSource": "/api/taxcore/dashboard-stats/{org_id}",
                "metric": "total_amount_submitted",
                "format": "currency",
                "icon": "fa-dollar-sign",
                "trend": {
                    "enabled": true,
                    "comparison": "previous_period"
                }
            },
            {
                "id": "retry_queue",
                "type": "alert",
                "title": "Retry Queue",
                "size": "full",
                "dataSource": "/api/taxcore/dashboard-stats/{org_id}",
                "alerts": [
                    {
                        "key": "queued_for_retry",
                        "label": "Submissions Queued",
                        "icon": "fa-redo",
                        "severity": "info",
                        "condition": "queued_for_retry > 0"
                    },
                    {
                        "key": "max_retries_exceeded",
                        "label": "Max Retries Exceeded",
                        "icon": "fa-exclamation-triangle",
                        "severity": "error",
                        "condition": "max_retries_exceeded > 0",
                        "action": {
                            "label": "View Submissions",
                            "link": "/taxcore/submissions?status=failed"
                        }
                    }
                ]
            },
            {
                "id": "recent_submissions",
                "type": "list",
                "title": "Recent Submissions",
                "size": "full",
                "dataSource": {
                    "url": "/api/taxcore/submission-history/{org_id}",
                    "params": {"limit": 10, "offset": 0}
                },
                "columns": [
                    {"key": "invoice_number", "label": "Invoice #"},
                    {"key": "status", "label": "Status", "type": "badge"},
                    {"key": "total_amount", "label": "Amount", "type": "currency"},
                    {"key": "created_at", "label": "Time", "type": "datetime"}
                ],
                "actions": [
                    {"label": "View All", "link": "/taxcore/submissions"}
                ]
            },
            {
                "id": "submission_trend",
                "type": "chart",
                "title": "Submission Trend (7 Days)",
                "size": "full",
                "chartType": "line",
                "dataSource": "/api/taxcore/submission-trend/{org_id}?days=7",
                "xAxis": "date",
                "yAxis": [
                    {"key": "success", "label": "Successful", "color": "#10b981"},
                    {"key": "failed", "label": "Failed", "color": "#ef4444"}
                ]
            }
        ],
        "actions": [
            {
                "label": "View All Submissions",
                "icon": "fa-list",
                "link": "/taxcore/submissions"
            },
            {
                "label": "Configuration",
                "icon": "fa-cog",
                "link": "/taxcore/configuration"
            }
        ]
    }'::jsonb,
    true,
    NOW(),
    NOW()
) ON CONFLICT (name) DO UPDATE SET
    config = EXCLUDED.config,
    updated_at = NOW();

-- ============================================================================
-- Module 3: TaxCore Configuration
-- ============================================================================
-- Purpose: Org-specific TaxCore settings management
-- ============================================================================

INSERT INTO modules (
    module_id,
    name,
    title,
    icon,
    category,
    description,
    config,
    is_active,
    created_at,
    updated_at
) VALUES (
    uuid_generate_v7(),
    'TaxCoreConfiguration',
    'TaxCore Configuration',
    'fa-cog',
    'settings',
    'Configure TaxCore API settings for your organization',
    '{
        "type": "form",
        "dataSource": {
            "get": "/api/taxcore/configuration/{org_id}",
            "save": "/api/taxcore/configuration",
            "method": "POST"
        },
        "sections": [
            {
                "title": "API Configuration",
                "fields": [
                    {
                        "key": "api_base_url",
                        "label": "API Base URL",
                        "type": "text",
                        "placeholder": "https://sandbox.vms.frcs.org.fj:8888",
                        "required": true,
                        "help": "TaxCore API endpoint (sandbox or production)"
                    },
                    {
                        "key": "org_tin",
                        "label": "Organization TIN",
                        "type": "text",
                        "placeholder": "20f351f3-9b39-4c63-b9e0-d8a00b6e93fb",
                        "required": true,
                        "help": "Your organization Tax Identification Number in TaxCore"
                    },
                    {
                        "key": "api_version",
                        "label": "API Version",
                        "type": "select",
                        "options": [
                            {"value": "v3", "label": "Version 3 (Current)"},
                            {"value": "v2", "label": "Version 2 (Legacy)"}
                        ],
                        "default": "v3",
                        "required": true
                    }
                ]
            },
            {
                "title": "Certificate Configuration",
                "fields": [
                    {
                        "key": "certificate_file",
                        "label": "Certificate File (.pfx)",
                        "type": "file",
                        "accept": ".pfx,.p12",
                        "maxSize": "5MB",
                        "help": "Upload your P12/PFX certificate for API authentication"
                    },
                    {
                        "key": "certificate_password",
                        "label": "Certificate Password",
                        "type": "password",
                        "help": "Password to decrypt the certificate",
                        "encrypted": true
                    },
                    {
                        "key": "certificate_expiry",
                        "label": "Certificate Expiry",
                        "type": "date",
                        "readonly": true,
                        "help": "Automatically detected from certificate"
                    }
                ]
            },
            {
                "title": "Submission Settings",
                "fields": [
                    {
                        "key": "auto_submit_invoices",
                        "label": "Auto-Submit Invoices",
                        "type": "checkbox",
                        "default": true,
                        "help": "Automatically submit invoices when finalized"
                    },
                    {
                        "key": "auto_submit_receipts",
                        "label": "Auto-Submit Sales Receipts",
                        "type": "checkbox",
                        "default": true,
                        "help": "Automatically submit POS sales receipts"
                    },
                    {
                        "key": "default_submission_type",
                        "label": "Default Submission Type",
                        "type": "select",
                        "options": [
                            {"value": "Normal", "label": "Normal"},
                            {"value": "Training", "label": "Training"},
                            {"value": "Proforma", "label": "Proforma"}
                        ],
                        "default": "Normal"
                    },
                    {
                        "key": "retry_max_attempts",
                        "label": "Max Retry Attempts",
                        "type": "number",
                        "min": 1,
                        "max": 10,
                        "default": 5,
                        "help": "Maximum number of retry attempts for failed submissions"
                    },
                    {
                        "key": "retry_delay_minutes",
                        "label": "Initial Retry Delay (minutes)",
                        "type": "number",
                        "min": 1,
                        "max": 60,
                        "default": 5,
                        "help": "Base delay before first retry (exponential backoff applied)"
                    }
                ]
            },
            {
                "title": "Environment",
                "fields": [
                    {
                        "key": "is_sandbox",
                        "label": "Use Sandbox Environment",
                        "type": "checkbox",
                        "default": true,
                        "help": "Enable for testing, disable for production submissions"
                    },
                    {
                        "key": "is_active",
                        "label": "Enable TaxCore Integration",
                        "type": "checkbox",
                        "default": true,
                        "help": "Master switch to enable/disable TaxCore for this org"
                    }
                ]
            }
        ],
        "actions": [
            {
                "label": "Test Connection",
                "icon": "fa-plug",
                "action": "taxcore:test-connection",
                "color": "info",
                "confirm": "Test connection to TaxCore API?"
            },
            {
                "label": "Save Configuration",
                "icon": "fa-save",
                "action": "save",
                "color": "primary",
                "type": "submit"
            }
        ],
        "validation": {
            "api_base_url": "required|url",
            "org_tin": "required|uuid",
            "certificate_password": "required_if:certificate_file"
        }
    }'::jsonb,
    true,
    NOW(),
    NOW()
) ON CONFLICT (name) DO UPDATE SET
    config = EXCLUDED.config,
    updated_at = NOW();

-- ============================================================================
-- Module 4: Failed Submissions Alert
-- ============================================================================
-- Purpose: Real-time alert component for failed submissions
-- ============================================================================

INSERT INTO modules (
    module_id,
    name,
    title,
    icon,
    category,
    description,
    config,
    is_active,
    created_at,
    updated_at
) VALUES (
    uuid_generate_v7(),
    'TaxCoreFailedAlert',
    'TaxCore Failed Submissions',
    'fa-exclamation-triangle',
    'alerts',
    'Alert widget for failed TaxCore submissions requiring attention',
    '{
        "type": "alert",
        "refreshInterval": 10000,
        "dataSource": {
            "url": "/api/taxcore/submission-history/{org_id}",
            "params": {
                "status": "failed",
                "limit": 10
            }
        },
        "severity": "error",
        "dismissible": false,
        "icon": "fa-exclamation-triangle",
        "title": "TaxCore Submissions Failed",
        "template": "{count} submission(s) failed and require attention",
        "showWhen": "count > 0",
        "actions": [
            {
                "label": "View Details",
                "icon": "fa-eye",
                "link": "/taxcore/submissions?status=failed"
            },
            {
                "label": "Retry All",
                "icon": "fa-redo",
                "action": "taxcore:retry-all-failed",
                "confirm": "Retry all failed submissions?"
            }
        ],
        "sound": {
            "enabled": true,
            "file": "alert.mp3",
            "playWhen": "count > previous_count"
        }
    }'::jsonb,
    true,
    NOW(),
    NOW()
) ON CONFLICT (name) DO UPDATE SET
    config = EXCLUDED.config,
    updated_at = NOW();

-- ============================================================================
-- Navigation Menu Entries
-- ============================================================================

-- Add TaxCore menu section to main navigation
-- This would typically be inserted into a navigation/menu table if one exists

-- ============================================================================
-- Permissions Setup
-- ============================================================================

-- Grant permissions for TaxCore modules (assuming permissions table exists)
-- INSERT INTO permissions (permission_id, module_name, action, role) VALUES
-- (uuid_generate_v7(), 'TaxCoreSubmissions', 'view', 'admin'),
-- (uuid_generate_v7(), 'TaxCoreSubmissions', 'retry', 'admin'),
-- (uuid_generate_v7(), 'TaxCoreDashboard', 'view', 'admin'),
-- (uuid_generate_v7(), 'TaxCoreConfiguration', 'edit', 'admin');

-- ============================================================================
-- Verification Queries
-- ============================================================================

-- List all TaxCore modules
-- SELECT module_id, name, title, category, is_active FROM modules WHERE name LIKE '%TaxCore%';

-- Get module configuration
-- SELECT name, config->'type' as module_type, config->'dataSource' as data_source FROM modules WHERE category = 'finance';

-- Count active modules
-- SELECT COUNT(*) as active_modules FROM modules WHERE is_active = true AND name LIKE '%TaxCore%';
