-- ==============================================================================
-- Custom SmoothSchedule Pieces Metadata
-- ==============================================================================
-- This script registers custom pieces in the Activepieces database.
-- It runs on container startup via publish-pieces.sh.
--
-- IMPORTANT:
--   - Pieces use pieceType=CUSTOM with platformId to avoid being deleted by sync
--   - This script is IDEMPOTENT - safe to run multiple times
--   - If platform doesn't exist yet, this script will silently skip
-- ==============================================================================

-- Get the platform ID dynamically and only proceed if platform exists
DO $$
DECLARE
    platform_id varchar(21);
    platform_count integer;
BEGIN
    -- Check if platform table exists and has data
    SELECT COUNT(*) INTO platform_count FROM platform;

    IF platform_count = 0 THEN
        RAISE NOTICE 'No platform found yet - skipping piece metadata registration';
        RAISE NOTICE 'Pieces will be registered on next container restart after platform is created';
        RETURN;
    END IF;

    SELECT id INTO platform_id FROM platform LIMIT 1;
    RAISE NOTICE 'Registering custom pieces for platform: %', platform_id;

    -- Pin our custom pieces in the platform so they appear first
    UPDATE platform
    SET "pinnedPieces" = ARRAY[
        '@activepieces/piece-smoothschedule',
        '@activepieces/piece-python-code',
        '@activepieces/piece-ruby-code'
    ]::varchar[]
    WHERE id = platform_id
    AND ("pinnedPieces" = '{}' OR "pinnedPieces" IS NULL OR NOT '@activepieces/piece-smoothschedule' = ANY("pinnedPieces"));

    -- Delete existing entries for our custom pieces (to avoid ID conflicts)
    DELETE FROM piece_metadata WHERE name IN (
        '@activepieces/piece-smoothschedule',
        '@activepieces/piece-python-code',
        '@activepieces/piece-ruby-code',
        '@activepieces/piece-interfaces'
    );

    -- SmoothSchedule piece
    INSERT INTO piece_metadata (
        id, name, "displayName", "logoUrl", description, version,
        "minimumSupportedRelease", "maximumSupportedRelease",
        actions, triggers, auth, "pieceType", "packageType", categories, authors, "projectUsage", "platformId"
    ) VALUES (
        'smoothschedule001',
        '@activepieces/piece-smoothschedule',
        'SmoothSchedule',
        'https://api.smoothschedule.com/images/logo-branding.png',
        'Scheduling and appointment management for your business',
        '0.0.1',
        '0.36.1',
        '99999.99999.9999',
        '{"create_event":{"name":"create_event","displayName":"Create Event","description":"Create a new event/appointment","props":{},"requireAuth":true,"errorHandlingOptions":{"continueOnFailure":{"defaultValue":false},"retryOnFailure":{"defaultValue":false}}},"update_event":{"name":"update_event","displayName":"Update Event","description":"Update an existing event","props":{},"requireAuth":true,"errorHandlingOptions":{"continueOnFailure":{"defaultValue":false},"retryOnFailure":{"defaultValue":false}}},"cancel_event":{"name":"cancel_event","displayName":"Cancel Event","description":"Cancel an event","props":{},"requireAuth":true,"errorHandlingOptions":{"continueOnFailure":{"defaultValue":false},"retryOnFailure":{"defaultValue":false}}},"find_events":{"name":"find_events","displayName":"Find Events","description":"Search for events","props":{},"requireAuth":true,"errorHandlingOptions":{"continueOnFailure":{"defaultValue":false},"retryOnFailure":{"defaultValue":false}}},"list_resources":{"name":"list_resources","displayName":"List Resources","description":"List all resources","props":{},"requireAuth":true,"errorHandlingOptions":{"continueOnFailure":{"defaultValue":false},"retryOnFailure":{"defaultValue":false}}},"list_services":{"name":"list_services","displayName":"List Services","description":"List all services","props":{},"requireAuth":true,"errorHandlingOptions":{"continueOnFailure":{"defaultValue":false},"retryOnFailure":{"defaultValue":false}}},"list_inactive_customers":{"name":"list_inactive_customers","displayName":"List Inactive Customers","description":"List customers who havent booked recently","props":{},"requireAuth":true,"errorHandlingOptions":{"continueOnFailure":{"defaultValue":false},"retryOnFailure":{"defaultValue":false}}},"send_email":{"name":"send_email","displayName":"Send Email","description":"Send an email using a SmoothSchedule email template","props":{},"requireAuth":true,"errorHandlingOptions":{"continueOnFailure":{"defaultValue":false},"retryOnFailure":{"defaultValue":false}}},"list_email_templates":{"name":"list_email_templates","displayName":"List Email Templates","description":"Get all available email templates","props":{},"requireAuth":true,"errorHandlingOptions":{"continueOnFailure":{"defaultValue":false},"retryOnFailure":{"defaultValue":false}}},"custom_api_call":{"name":"custom_api_call","displayName":"Custom API Call","description":"Make a custom API request","props":{},"requireAuth":true,"errorHandlingOptions":{"continueOnFailure":{"defaultValue":false},"retryOnFailure":{"defaultValue":false}}}}',
        '{"event_created":{"name":"event_created","displayName":"Event Created","description":"Triggers when a new event is created","props":{},"type":"WEBHOOK","handshakeConfiguration":{"strategy":"NONE"},"requireAuth":true,"testStrategy":"SIMULATION"},"event_updated":{"name":"event_updated","displayName":"Event Updated","description":"Triggers when an event is updated","props":{},"type":"WEBHOOK","handshakeConfiguration":{"strategy":"NONE"},"requireAuth":true,"testStrategy":"SIMULATION"},"event_cancelled":{"name":"event_cancelled","displayName":"Event Cancelled","description":"Triggers when an event is cancelled","props":{},"type":"WEBHOOK","handshakeConfiguration":{"strategy":"NONE"},"requireAuth":true,"testStrategy":"SIMULATION"},"event_status_changed":{"name":"event_status_changed","displayName":"Event Status Changed","description":"Triggers when event status changes","props":{},"type":"WEBHOOK","handshakeConfiguration":{"strategy":"NONE"},"requireAuth":true,"testStrategy":"SIMULATION"}}',
        '{"type":"CUSTOM_AUTH","displayName":"Connection","description":"Connect to your SmoothSchedule account","required":true,"props":{"baseUrl":{"displayName":"API URL","description":"Your SmoothSchedule API URL","required":true,"type":"SECRET_TEXT"},"apiToken":{"displayName":"API Token","description":"Your API token from Settings","required":true,"type":"SECRET_TEXT"}}}',
        'CUSTOM',
        'REGISTRY',
        ARRAY['PRODUCTIVITY', 'SALES_AND_CRM'],
        ARRAY['smoothschedule'],
        100,
        platform_id
    );

    -- Python Code piece
    INSERT INTO piece_metadata (
        id, name, "displayName", "logoUrl", description, version,
        "minimumSupportedRelease", "maximumSupportedRelease",
        actions, triggers, auth, "pieceType", "packageType", categories, authors, "projectUsage", "platformId"
    ) VALUES (
        'pythoncode00001',
        '@activepieces/piece-python-code',
        'Python Code',
        'https://api.smoothschedule.com/images/python-logo.svg',
        'Execute custom Python code in your workflows',
        '0.0.1',
        '0.36.1',
        '99999.99999.9999',
        '{"run_python":{"name":"run_python","displayName":"Run Python Code","description":"Execute Python code and return results","props":{"code":{"displayName":"Python Code","description":"The Python code to execute","required":true,"type":"LONG_TEXT"}},"requireAuth":false,"errorHandlingOptions":{"continueOnFailure":{"defaultValue":false},"retryOnFailure":{"defaultValue":false}}}}',
        '{}',
        NULL,
        'CUSTOM',
        'REGISTRY',
        ARRAY['DEVELOPER_TOOLS'],
        ARRAY['smoothschedule'],
        0,
        platform_id
    );

    -- Ruby Code piece
    INSERT INTO piece_metadata (
        id, name, "displayName", "logoUrl", description, version,
        "minimumSupportedRelease", "maximumSupportedRelease",
        actions, triggers, auth, "pieceType", "packageType", categories, authors, "projectUsage", "platformId"
    ) VALUES (
        'rubycode000001',
        '@activepieces/piece-ruby-code',
        'Ruby Code',
        'https://api.smoothschedule.com/images/ruby-logo.svg',
        'Execute custom Ruby code in your workflows',
        '0.0.1',
        '0.36.1',
        '99999.99999.9999',
        '{"run_ruby":{"name":"run_ruby","displayName":"Run Ruby Code","description":"Execute Ruby code and return results","props":{"code":{"displayName":"Ruby Code","description":"The Ruby code to execute","required":true,"type":"LONG_TEXT"}},"requireAuth":false,"errorHandlingOptions":{"continueOnFailure":{"defaultValue":false},"retryOnFailure":{"defaultValue":false}}}}',
        '{}',
        NULL,
        'CUSTOM',
        'REGISTRY',
        ARRAY['DEVELOPER_TOOLS'],
        ARRAY['smoothschedule'],
        0,
        platform_id
    );
END $$;
