-- Create Test API Key for MCP SDK Testing
-- This script inserts a test API key directly into the database
-- API Key: cola_test_runtime_validation_2025

DO $$
DECLARE
    test_tenant_id UUID := '00000000-0000-0000-0000-000000000001';
    test_user_id UUID := '00000000-0000-0000-0000-000000000001';
    test_api_key_id UUID := gen_random_uuid();
    plain_key TEXT := 'cola_test_runtime_validation_2025';
    -- SHA-256 hash of 'cola_test_runtime_validation_2025'
    key_hash TEXT := encode(digest(plain_key, 'sha256'), 'hex');
    key_prefix TEXT := substring(plain_key, 1, 12) || '...';
BEGIN
    -- Insert test API key
    INSERT INTO mcp.api_keys (
        id,
        name,
        description,
        key_hash,
        key_prefix,
        tenant_id,
        created_by,
        "read",
        write,
        allowed_resources,
        allowed_tools,
        ip_whitelist,
        expires_at,
        created_at,
        last_used_at,
        revoked_at,
        revoked_by
    ) VALUES (
        test_api_key_id,
        'SDK Runtime Test Key',
        'Auto-generated test key for MCP SDK runtime validation',
        key_hash,
        key_prefix,
        test_tenant_id,
        test_user_id,
        true,  -- read permission
        true,  -- write permission
        '{}',  -- empty array = all resources allowed
        '{}',  -- empty array = all tools allowed
        '{}',  -- empty array = no IP whitelist
        NOW() + INTERVAL '30 days',  -- expires in 30 days
        NOW(),
        NULL,  -- never used
        NULL,  -- not revoked
        NULL
    )
    ON CONFLICT (id) DO NOTHING;

    RAISE NOTICE 'Test API Key created successfully!';
    RAISE NOTICE 'API Key ID: %', test_api_key_id;
    RAISE NOTICE 'Plain Key (save this!): %', plain_key;
    RAISE NOTICE 'Key Prefix: %', key_prefix;
    RAISE NOTICE 'Expires At: %', (NOW() + INTERVAL '30 days')::TEXT;
END $$;
