-- ==============================================================================
-- Custom SmoothSchedule Pieces Configuration
-- ==============================================================================
-- This script configures pinned pieces for the Activepieces platform.
-- It runs on container startup via docker-entrypoint.sh.
--
-- NOTE: We do NOT insert pieces into piece_metadata because they are already
-- built into the Docker image in packages/pieces/community/. Activepieces
-- auto-discovers these as OFFICIAL pieces. Adding them to piece_metadata
-- would create duplicates in the UI.
--
-- We ONLY set pinnedPieces to make our pieces appear first in Highlights.
-- ==============================================================================

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 configuration';
        RAISE NOTICE 'Pieces will be configured on next container restart after platform is created';
        RETURN;
    END IF;

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

    -- Remove any duplicate CUSTOM entries for pieces that are built into the image
    -- These cause duplicates in the UI since they're also discovered from filesystem
    DELETE FROM piece_metadata WHERE name IN (
        '@activepieces/piece-smoothschedule',
        '@activepieces/piece-python-code',
        '@activepieces/piece-ruby-code',
        '@activepieces/piece-interfaces'
    ) AND "pieceType" = 'CUSTOM';

    IF FOUND THEN
        RAISE NOTICE 'Removed duplicate CUSTOM piece entries';
    END IF;

    -- Pin our pieces in the platform so they appear first in Highlights
    -- This works with pieces auto-discovered from the filesystem
    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"));

    RAISE NOTICE 'Piece configuration complete';
END $$;
