-- ============================================================================
-- Phase 6: TaxCore Modules (Schema-Compatible Version)
-- ============================================================================
-- Compatible with existing modules table structure (uses config JSONB column)
-- ============================================================================

-- Module 1: TaxCoreSubmissions (List Module)
INSERT INTO modules (name, icon, aria_label, description, config)
VALUES (
    'TaxCoreSubmissions',
    'fa-file-invoice',
    'TaxCore Submissions List',
    'View and manage TaxCore submission history',
    '{
        "type": "list",
        "dataSource": "/api/taxcore/submission-history/{org_id}",
        "pagination": true,
        "refresh": 30000,
        "filters": [
            {"key": "status", "type": "select", "label": "Status", "options": ["pending", "success", "failed", "queued"]},
            {"key": "submission_type", "type": "select", "label": "Type", "options": ["invoices", "sales_receipts"]},
            {"key": "date_from", "type": "date", "label": "From Date"},
            {"key": "date_to", "type": "date", "label": "To Date"}
        ],
        "columns": [
            {"key": "submission_id", "label": "Submission ID", "type": "uuid", "copyable": true, "width": "250px"},
            {"key": "status", "label": "Status", "type": "badge", "badges": {
                "pending": {"class": "badge-warning", "icon": "fa-clock"},
                "success": {"class": "badge-success", "icon": "fa-check"},
                "failed": {"class": "badge-error", "icon": "fa-times"},
                "queued": {"class": "badge-info", "icon": "fa-hourglass"}
            }},
            {"key": "reference_table", "label": "Type", "type": "text"},
            {"key": "invoice_number", "label": "Invoice #", "type": "text"},
            {"key": "taxcore_invoice_number", "label": "TaxCore #", "type": "text", "copyable": true},
            {"key": "total_amount", "label": "Amount", "type": "currency", "currency": "USD"},
            {"key": "attempts", "label": "Attempts", "type": "number"},
            {"key": "created_at", "label": "Created", "type": "datetime", "format": "YYYY-MM-DD HH:mm"}
        ],
        "rowActions": [
            {"label": "View Details", "action": "taxcore:view", "icon": "fa-eye"},
            {"label": "Retry", "action": "taxcore:retry", "icon": "fa-redo", "condition": "status == \"failed\"", "confirm": "Retry this submission?"},
            {"label": "View PDF", "action": "taxcore:pdf", "icon": "fa-file-pdf", "condition": "status == \"success\" && taxcore_url != null"},
            {"label": "Copy URL", "action": "taxcore:copy-url", "icon": "fa-link", "condition": "taxcore_url != null"}
        ],
        "bulkActions": [
            {"label": "Retry Selected", "action": "taxcore:bulk-retry", "icon": "fa-redo", "confirm": "Retry {count} submissions?"},
            {"label": "Export CSV", "action": "export:csv", "icon": "fa-download"}
        ]
    }'::jsonb
)
ON CONFLICT (name) DO UPDATE
SET config = EXCLUDED.config,
    icon = EXCLUDED.icon,
    aria_label = EXCLUDED.aria_label,
    description = EXCLUDED.description;

-- Module 2: TaxCoreDashboard (Dashboard Module)
INSERT INTO modules (name, icon, aria_label, description, config)
VALUES (
    'TaxCoreDashboard',
    'fa-chart-line',
    'TaxCore Dashboard',
    'Real-time TaxCore submission monitoring dashboard',
    '{
        "type": "dashboard",
        "refreshInterval": 30000,
        "widgets": [
            {
                "id": "stats_overview",
                "type": "stats",
                "title": "Submission Overview",
                "dataSource": "/api/taxcore/stats/{org_id}",
                "stats": [
                    {"key": "total_submissions", "label": "Total", "icon": "fa-file-invoice", "class": "stat-primary"},
                    {"key": "successful", "label": "Successful", "icon": "fa-check-circle", "class": "stat-success"},
                    {"key": "failed", "label": "Failed", "icon": "fa-times-circle", "class": "stat-error"},
                    {"key": "pending", "label": "Pending", "icon": "fa-clock", "class": "stat-warning"}
                ]
            },
            {
                "id": "success_rate",
                "type": "gauge",
                "title": "Success Rate",
                "dataSource": "/api/taxcore/stats/{org_id}",
                "calculate": "(successful / total_submissions) * 100",
                "unit": "%",
                "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",
                "dataSource": "/api/taxcore/stats/{org_id}",
                "key": "total_amount",
                "format": "currency",
                "currency": "USD",
                "trend": {"enabled": true, "period": "7d"}
            },
            {
                "id": "retry_queue",
                "type": "alert",
                "title": "Retry Queue",
                "dataSource": "/api/taxcore/queue-stats/{org_id}",
                "alerts": [
                    {"key": "queued_for_retry", "label": "Queued for Retry", "icon": "fa-hourglass", "severity": "warning"},
                    {"key": "max_retries_exceeded", "label": "Max Retries Exceeded", "icon": "fa-exclamation-triangle", "severity": "error"}
                ]
            },
            {
                "id": "recent_submissions",
                "type": "list",
                "title": "Recent Submissions",
                "dataSource": "/api/taxcore/submission-history/{org_id}?limit=10&sort=created_at:desc",
                "columns": [
                    {"key": "submission_id", "label": "ID", "type": "uuid", "truncate": 8},
                    {"key": "status", "label": "Status", "type": "badge"},
                    {"key": "invoice_number", "label": "Invoice #"},
                    {"key": "total_amount", "label": "Amount", "type": "currency"},
                    {"key": "created_at", "label": "Created", "type": "datetime", "format": "relative"}
                ]
            },
            {
                "id": "submission_trend",
                "type": "chart",
                "title": "Submission Trend (7 Days)",
                "chartType": "line",
                "dataSource": "/api/taxcore/submission-trend/{org_id}?days=7",
                "xAxis": "date",
                "yAxis": ["success", "failed"],
                "colors": ["#10b981", "#ef4444"]
            }
        ]
    }'::jsonb
)
ON CONFLICT (name) DO UPDATE
SET config = EXCLUDED.config,
    icon = EXCLUDED.icon,
    aria_label = EXCLUDED.aria_label,
    description = EXCLUDED.description;

-- Module 3: TaxCoreConfiguration (Form Module)
INSERT INTO modules (name, icon, aria_label, description, config)
VALUES (
    'TaxCoreConfiguration',
    'fa-cog',
    'TaxCore Configuration',
    'Configure TaxCore API settings for your organization',
    '{
        "type": "form",
        "dataSource": "/api/taxcore/configuration/{org_id}",
        "submitEndpoint": "/api/taxcore/configuration",
        "sections": [
            {
                "title": "API Configuration",
                "fields": [
                    {"key": "api_base_url", "label": "API Base URL", "type": "url", "required": true, "placeholder": "https://taxcore-api.example.com", "validation": "url"},
                    {"key": "org_tin", "label": "Organization TIN", "type": "text", "required": true, "placeholder": "1234567890", "validation": "uuid"},
                    {"key": "api_version", "label": "API Version", "type": "select", "options": ["v1", "v2"], "default": "v1"}
                ]
            },
            {
                "title": "Certificate Configuration",
                "fields": [
                    {"key": "certificate_file", "label": "Certificate File", "type": "file", "accept": ".pfx,.p12", "required": true, "help": "PKCS#12 certificate file"},
                    {"key": "certificate_password", "label": "Certificate Password", "type": "password", "encrypted": true, "required": true},
                    {"key": "certificate_expiry", "label": "Certificate Expiry", "type": "date", "readonly": true, "computed": "extractExpiryFromCertificate"}
                ]
            },
            {
                "title": "Submission Settings",
                "fields": [
                    {"key": "auto_submit_invoices", "label": "Auto-submit Invoices", "type": "toggle", "default": true, "help": "Automatically submit finalized invoices to TaxCore"},
                    {"key": "auto_submit_receipts", "label": "Auto-submit Receipts", "type": "toggle", "default": true, "help": "Automatically submit sales receipts to TaxCore"},
                    {"key": "retry_max_attempts", "label": "Max Retry Attempts", "type": "number", "min": 1, "max": 10, "default": 5},
                    {"key": "retry_base_delay", "label": "Base Retry Delay (minutes)", "type": "number", "min": 1, "max": 60, "default": 5},
                    {"key": "retry_backoff_multiplier", "label": "Backoff Multiplier", "type": "number", "min": 1, "max": 5, "step": 0.5, "default": 2}
                ]
            },
            {
                "title": "Environment",
                "fields": [
                    {"key": "is_sandbox", "label": "Sandbox Mode", "type": "toggle", "default": false, "help": "Use sandbox environment for testing"},
                    {"key": "is_active", "label": "Active", "type": "toggle", "default": true, "help": "Enable TaxCore integration"}
                ]
            }
        ],
        "actions": [
            {"label": "Test Connection", "action": "taxcore:test-connection", "icon": "fa-plug", "type": "button", "class": "btn-outline"},
            {"label": "Save Configuration", "type": "submit", "icon": "fa-save", "class": "btn-primary"}
        ],
        "validation": {
            "api_base_url": {"pattern": "^https?://", "message": "Must be a valid HTTP/HTTPS URL"},
            "org_tin": {"pattern": "^[0-9a-fA-F-]{36}$", "message": "Must be a valid UUID"},
            "retry_max_attempts": {"min": 1, "max": 10, "message": "Must be between 1 and 10"}
        }
    }'::jsonb
)
ON CONFLICT (name) DO UPDATE
SET config = EXCLUDED.config,
    icon = EXCLUDED.icon,
    aria_label = EXCLUDED.aria_label,
    description = EXCLUDED.description;

-- Module 4: TaxCoreFailedAlert (Alert Module)
INSERT INTO modules (name, icon, aria_label, description, config)
VALUES (
    'TaxCoreFailedAlert',
    'fa-exclamation-triangle',
    'TaxCore Failed Submissions Alert',
    'Real-time alert for failed TaxCore submissions',
    '{
        "type": "alert",
        "severity": "error",
        "refreshInterval": 10000,
        "dataSource": "/api/taxcore/failed-count/{org_id}",
        "showWhen": "count > 0",
        "template": "{count} TaxCore submission(s) failed and require attention",
        "actions": [
            {"label": "View Details", "link": "/taxcore/submissions?status=failed", "icon": "fa-list"},
            {"label": "Retry All", "action": "taxcore:retry-all-failed", "icon": "fa-redo", "confirm": "Retry all failed submissions?"}
        ],
        "sound": {
            "enabled": true,
            "playWhen": "count > previous_count",
            "file": "/sounds/alert.mp3"
        },
        "position": "top-right",
        "dismissible": false
    }'::jsonb
)
ON CONFLICT (name) DO UPDATE
SET config = EXCLUDED.config,
    icon = EXCLUDED.icon,
    aria_label = EXCLUDED.aria_label,
    description = EXCLUDED.description;

-- Add comments
COMMENT ON TABLE modules IS 'Module definitions for Phase 6 TaxCore monitoring dashboard';
