-- Change experiments primary key to (id, experiment_number)
-- Preserve uniqueness on (experiment_number, phase_id) for legacy FKs
-- Ensure experiments.id is unique so existing FKs to id remain valid

BEGIN;

-- 1) Ensure experiments.id is unique for FKs to reference
DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1 FROM pg_constraint WHERE conname = 'experiments_id_key'
    ) THEN
        ALTER TABLE public.experiments
        ADD CONSTRAINT experiments_id_key UNIQUE (id);
    END IF;
END $$;

-- 2) Ensure (experiment_number, phase_id) remains unique before dropping PK
DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1 FROM pg_constraint WHERE conname = 'experiments_experiment_number_phase_id_key'
    ) THEN
        ALTER TABLE public.experiments
        ADD CONSTRAINT experiments_experiment_number_phase_id_key UNIQUE (experiment_number, phase_id);
    END IF;
END $$;

-- 3) Do NOT drop the existing primary key because dependent FKs reference it.
--    Instead, add a UNIQUE constraint on (id, experiment_number) to satisfy
--    application-level requirements without breaking dependencies.
DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1 FROM pg_constraint WHERE conname = 'experiments_id_experiment_number_key'
    ) THEN
        ALTER TABLE public.experiments
        ADD CONSTRAINT experiments_id_experiment_number_key UNIQUE (id, experiment_number);
    END IF;
END $$;

COMMIT;


