DO $$ 
BEGIN
    -- 1. Rename Tables
    IF EXISTS (SELECT FROM pg_tables WHERE schemaname = 'public' AND tablename = 'potenziali') THEN
        ALTER TABLE public.potenziali RENAME TO appunti;
    END IF;

    IF EXISTS (SELECT FROM pg_tables WHERE schemaname = 'public' AND tablename = 'potenziali_groups') THEN
        ALTER TABLE public.potenziali_groups RENAME TO appunti_groups;
    END IF;

    -- 2. Rename Column (IF EXISTS is supported here in PG 10+)
    IF EXISTS (SELECT FROM information_schema.columns WHERE table_name='appunti' AND column_name='potenziali_group_id') THEN
        ALTER TABLE public.appunti RENAME COLUMN potenziali_group_id TO appunti_group_id;
    END IF;

    -- 3. Rename Constraints (Requires manual check because RENAME CONSTRAINT IF EXISTS doesn't exist)
    IF EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'potenziali_pkey') THEN
        ALTER TABLE public.appunti RENAME CONSTRAINT potenziali_pkey TO appunti_pkey;
    END IF;

    IF EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'potenziali_assigned_user') THEN
        ALTER TABLE public.appunti RENAME CONSTRAINT potenziali_assigned_user TO appunti_assigned_user;
    END IF;

    IF EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'potenziali_group_fk') THEN
        ALTER TABLE public.appunti RENAME CONSTRAINT potenziali_group_fk TO appunti_group_fk;
    END IF;

    IF EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'potenziali_groups_pkey') THEN
        ALTER TABLE public.appunti_groups RENAME CONSTRAINT potenziali_groups_pkey TO appunti_groups_pkey;
    END IF;
END $$;