DO $$
BEGIN
    IF EXISTS (
        SELECT 1
        FROM information_schema.columns
        WHERE table_schema = 'public'
          AND table_name = 'facilities'
          AND column_name = 'cooperating_clubs'
          AND udt_name = 'text'
    ) THEN
        ALTER TABLE public.facilities
        RENAME COLUMN cooperating_clubs TO cooperating_clubs_legacy;
    END IF;

    IF NOT EXISTS (
        SELECT 1
        FROM information_schema.columns
        WHERE table_schema = 'public'
          AND table_name = 'facilities'
          AND column_name = 'cooperating_clubs'
    ) THEN
        ALTER TABLE public.facilities
        ADD COLUMN cooperating_clubs jsonb DEFAULT '[]'::jsonb;
    END IF;

    ALTER TABLE public.facilities
    ALTER COLUMN cooperating_clubs SET DEFAULT '[]'::jsonb;

    IF EXISTS (
        SELECT 1
        FROM information_schema.columns
        WHERE table_schema = 'public'
          AND table_name = 'facilities'
          AND column_name = 'cooperating_clubs_legacy'
    ) THEN
        UPDATE public.facilities
        SET cooperating_clubs = CASE
            WHEN cooperating_clubs_legacy IS NULL OR btrim(cooperating_clubs_legacy) = '' THEN '[]'::jsonb
            WHEN cooperating_clubs_legacy ~ '^\s*\[' THEN cooperating_clubs_legacy::jsonb
            ELSE to_jsonb(regexp_split_to_array(cooperating_clubs_legacy, '\s*,\s*'))
        END
        WHERE cooperating_clubs = '[]'::jsonb;

        ALTER TABLE public.facilities
        DROP COLUMN cooperating_clubs_legacy;
    END IF;
END $$;
