-- ============================================================================
-- Phase 6 Task 5: TaxCore Modules (Compatible with Existing Schema)
-- ============================================================================
-- 
-- This migration creates module definitions for TaxCore monitoring dashboard
-- Compatible with modules table schema: module_id, parent_module_id, name, 
-- config (JSONB), org_id, icon, branch_id, aria_label, description
-- 
-- ============================================================================

-- Module 1: TaxCore Submissions (List Module)
INSERT INTO modules (
    module_id,
    name,
    icon,
    description,
    config
)
VALUES (
    uuid_generate_v7(),
    'TaxCoreSubmissions',
    'fa-file-invoice',
    'TaxCore submission history with filters and actions',
    '{
        "type": "list",
        "dataSource": "/api/taxcore/submission-history/{org_id}",
        "pagination": true,
        "refreshInterval": 30000,
        "filters": [
            {
                "key": "status",
                "label": "Status",
                "type": "select",
                "options": [
                    {"value": "success", "label": "Success"},
                    {"value": "failed", "label": "Failed"},
                    {"value": "pending", "label": "Pending"},
                    {"value": "queued", "label": "Queued"}
                ]
            },
            {
                "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",
                "copyable": true,
                "width": "250px"
            },
            {
                "key": "status",
                "label": "Status",
                "type": "badge",
                "badges": {
                    "success": {"color": "success", "label": "Success"},
                    "failed": {"color": "error", "label": "Failed"},
                    "pending": {"color": "warning", "label": "Pending"},
                    "queued": {"color": "info", "label": "Queued"}
                }
            },
            {
                "key": "reference_table",
                "label": "Type",
                "type": "text"
            },
            {
                "key": "reference_id",
                "label": "Reference ID",
                "type": "uuid",
                "copyable": true
            },
            {
                "key": "taxcore_invoice_number",
                "label": "TaxCore Invoice #",
                "type": "text",
                "copyable": true
            },
            {
                "key": "total_amount",
                "label": "Amount",
                "type": "currency"
            },
            {
                "key": "attempts",
                "label": "Attempts",
                "type": "number"
            },
            {
                "key": "created_at",
                "label": "Created",
                "type": "datetime"
            }
        ],
        "rowActions": [
            {
                "label": "View Details",
                "icon": "fa-eye",
                "action": "taxcore:view",
                "color": "primary"
            },
            {
                "label": "Retry",
                "icon": "fa-redo",
                "action": "taxcore:retry",
                "condition": "status == \"failed\"",
                "confirm": "Retry this submission?",
                "color": "warning"
            },
            {
                "label": "View PDF",
                "icon": "fa-file-pdf",
                "action": "taxcore:pdf",
                "condition": "status == \"success\"",
                "color": "success"
            },
            {
                "label": "Copy URL",
                "icon": "fa-link",
                "action": "taxcore:copy-url",
                "condition": "taxcore_url != null",
                "color": "info"
            }
        ],
        "bulkActions": [
            {
                "label": "Retry Selected",
                "icon": "fa-redo",
                "action": "taxcore:bulk-retry",
                "confirm": "Retry all selected submissions?",
                "color": "warning"
            },
            {
                "label": "Export CSV",
                "icon": "fa-download",
                "action": "export:csv",
                "color": "secondary"
            }
        ]
    }'::jsonb
)
ON CONFLICT (name) DO UPDATE SET
    config = EXCLUDED.config,
    description = EXCLUDED.description,
    icon = EXCLUDED.icon,
    updatedat = NOW();

-- Module 2: TaxCore Dashboard (Dashboard Module)
INSERT INTO modules (
    module_id,
    name,
    icon,
    description,
    config
)
VALUES (
    uuid_generate_v7(),
    'TaxCoreDashboard',
    'fa-tachometer-alt',
    'TaxCore submission monitoring dashboard',
    '{
        "type": "dashboard",
        "refreshInterval": 30000,
        "layout": "grid",
        "widgets": [
            {
                "id": "stats_overview",
                "type": "stats",
                "title": "Submission Overview",
                "size": "full",
                "dataSource": "/api/taxcore/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"
                    },
                    {
                        "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",
                "size": "half",
                "dataSource": "/api/taxcore/stats/{org_id}",
                "calculate": "(successful / total_submissions) * 100",
                "min": 0,
                "max": 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",
                "size": "half",
                "dataSource": "/api/taxcore/stats/{org_id}",
                "key": "total_amount",
                "format": "currency",
                "trend": {
                    "enabled": true,
                    "compareWith": "previous_period"
                }
            },
            {
                "id": "retry_queue",
                "type": "alert",
                "title": "Retry Queue",
                "size": "full",
                "dataSource": "/api/taxcore/queue-stats/{org_id}",
                "alerts": [
                    {
                        "key": "queued_for_retry",
                        "label": "Items in Retry Queue",
                        "severity": "warning",
                        "threshold": 0,
                        "icon": "fa-hourglass-half"
                    },
                    {
                        "key": "max_retries_exceeded",
                        "label": "Max Retries Exceeded",
                        "severity": "error",
                        "threshold": 0,
                        "icon": "fa-exclamation-triangle"
                    }
                ]
            },
            {
                "id": "recent_submissions",
                "type": "list",
                "title": "Recent Submissions",
                "size": "full",
                "dataSource": "/api/taxcore/submission-history/{org_id}?limit=10",
                "columns": [
                    {"key": "created_at", "label": "Time", "type": "datetime"},
                    {"key": "reference_table", "label": "Type", "type": "text"},
                    {"key": "status", "label": "Status", "type": "badge"},
                    {"key": "total_amount", "label": "Amount", "type": "currency"}
                ]
            },
            {
                "id": "submission_trend",
                "type": "chart",
                "title": "7-Day Submission Trend",
                "size": "full",
                "dataSource": "/api/taxcore/trend/{org_id}?days=7",
                "chartType": "line",
                "xAxis": "date",
                "yAxis": ["successful", "failed"],
                "colors": {
                    "successful": "#10b981",
                    "failed": "#ef4444"
                }
            }
        ]
    }'::jsonb
)
ON CONFLICT (name) DO UPDATE SET
    config = EXCLUDED.config,
    description = EXCLUDED.description,
    icon = EXCLUDED.icon,
    updatedat = NOW();

-- Module 3: TaxCore Configuration (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/configuration/{org_id}",
        "submitUrl": "/api/taxcore/configuration/{org_id}",
        "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": "required"
                    },
                    {
                        "key": "api_version",
                        "label": "API Version",
                        "type": "select",
                        "required": true,
                        "options": [
                            {"value": "v1", "label": "Version 1"},
                            {"value": "v2", "label": "Version 2"}
                        ],
                        "default": "v1"
                    }
                ]
            },
            {
                "title": "Certificate Configuration",
                "fields": [
                    {
                        "key": "certificate_file",
                        "label": "Certificate File (.pfx or .p12)",
                        "type": "file",
                        "accept": ".pfx,.p12",
                        "required": true
                    },
                    {
                        "key": "certificate_password",
                        "label": "Certificate Password",
                        "type": "password",
                        "required": true,
                        "encrypted": true
                    },
                    {
                        "key": "certificate_expiry",
                        "label": "Certificate Expiry Date",
                        "type": "date",
                        "readonly": true
                    }
                ]
            },
            {
                "title": "Submission Settings",
                "fields": [
                    {
                        "key": "auto_submit_invoices",
                        "label": "Auto-submit Invoices",
                        "type": "toggle",
                        "default": true,
                        "help": "Automatically submit invoices when finalized"
                    },
                    {
                        "key": "auto_submit_receipts",
                        "label": "Auto-submit Sales Receipts",
                        "type": "toggle",
                        "default": true,
                        "help": "Automatically submit POS receipts in real-time"
                    },
                    {
                        "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.0
                    }
                ]
            },
            {
                "title": "Environment",
                "fields": [
                    {
                        "key": "is_sandbox",
                        "label": "Sandbox Mode",
                        "type": "toggle",
                        "default": false,
                        "help": "Use TaxCore sandbox environment for testing"
                    },
                    {
                        "key": "is_active",
                        "label": "Active",
                        "type": "toggle",
                        "default": true,
                        "help": "Enable/disable TaxCore integration"
                    }
                ]
            }
        ],
        "actions": [
            {
                "label": "Test Connection",
                "icon": "fa-plug",
                "action": "taxcore:test-connection",
                "color": "info",
                "type": "button"
            },
            {
                "label": "Save Configuration",
                "icon": "fa-save",
                "type": "submit",
                "color": "primary"
            }
        ]
    }'::jsonb
)
ON CONFLICT (name) DO UPDATE SET
    config = EXCLUDED.config,
    description = EXCLUDED.description,
    icon = EXCLUDED.icon,
    updatedat = NOW();

-- Module 4: TaxCore Failed Alert (Alert Module)
INSERT INTO modules (
    module_id,
    name,
    icon,
    description,
    config
)
VALUES (
    uuid_generate_v7(),
    'TaxCoreFailedAlert',
    'fa-exclamation-triangle',
    'Real-time 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",
        "actions": [
            {
                "label": "View Details",
                "icon": "fa-eye",
                "link": "/taxcore/submissions?status=failed",
                "color": "error"
            },
            {
                "label": "Retry All",
                "icon": "fa-redo",
                "action": "taxcore:retry-all-failed",
                "confirm": "Retry all failed submissions?",
                "color": "warning"
            }
        ],
        "sound": {
            "enabled": true,
            "playWhen": "count > previous_count",
            "file": "/sounds/alert.mp3"
        }
    }'::jsonb
)
ON CONFLICT (name) DO UPDATE SET
    config = EXCLUDED.config,
    description = EXCLUDED.description,
    icon = EXCLUDED.icon,
    updatedat = NOW();

-- ============================================================================
-- Verification
-- ============================================================================

-- Check created modules
SELECT 
    module_id,
    name,
    icon,
    description
FROM modules 
WHERE name LIKE '%TaxCore%'
ORDER BY name;

COMMENT ON TABLE modules IS 'Module definitions including TaxCore monitoring dashboard (Phase 6)';
