-- ALSO Cloud Marketplace email workflow action and default workflow

INSERT INTO email_workflow_actions (
    action_code,
    name,
    description,
    category,
    parameter_schema,
    example_config
)
VALUES (
    'process_also_cloud_billing',
    'Process ALSO Cloud Billing ZIP',
    'Downloader ALSO Cloud Marketplace billing ZIP fra email, importerer linjer og opretter ordrekladder',
    'billing',
    '{
        "type": "object",
        "properties": {
            "sender_pattern": {"type": "string"},
            "require_sender_match": {"type": "boolean"},
            "source_label": {"type": "string"},
            "imported_by_user_id": {"type": "integer"}
        }
    }'::jsonb,
    '{
        "sender_pattern": "no-reply@marketplace\\\\.also\\\\.dk",
        "require_sender_match": true,
        "source_label": "ALSO Cloud Marketplace email"
    }'::jsonb
)
ON CONFLICT (action_code) DO NOTHING;

INSERT INTO email_workflows (
    name,
    description,
    classification_trigger,
    sender_pattern,
    subject_pattern,
    confidence_threshold,
    workflow_steps,
    priority,
    enabled,
    stop_on_match,
    created_by_user_id
)
SELECT
    'ALSO Cloud Billing Import',
    'Matcher ALSO Cloud Marketplace billing-mails, downloader ZIP og opretter ordrekladder automatisk',
    'any',
    'marketplace\\.also\\.',
    'YOUR BILLING ZIP FILE IS READY TO BE DOWNLOADED|BILLING ZIP FILE',
    0.00,
    '[
        {
            "action": "process_also_cloud_billing",
            "params": {
                "sender_pattern": "marketplace\\.also\\.",
                "require_sender_match": true,
                "source_label": "ALSO Cloud Marketplace email"
            }
        }
    ]'::jsonb,
    15,
    true,
    true,
    1
WHERE NOT EXISTS (
    SELECT 1
    FROM email_workflows
    WHERE LOWER(name) = LOWER('ALSO Cloud Billing Import')
);
