-- Migration: Require cracking_machine_type_id when has_cracking is true

BEGIN;

-- Drop existing constraint if it exists (for re-runs)
DO $$
BEGIN
  IF EXISTS (
    SELECT 1 FROM pg_constraint c
    JOIN pg_class t ON c.conrelid = t.oid
    WHERE t.relname = 'experiment_phases'
      AND c.conname = 'ck_experiment_phases_machine_required_when_cracking'
  ) THEN
    ALTER TABLE public.experiment_phases
    DROP CONSTRAINT ck_experiment_phases_machine_required_when_cracking;
  END IF;
END $$;

-- Add check: if has_cracking then cracking_machine_type_id must not be null
ALTER TABLE public.experiment_phases
ADD CONSTRAINT ck_experiment_phases_machine_required_when_cracking
CHECK (
  (has_cracking = false) OR (cracking_machine_type_id IS NOT NULL)
);

COMMIT;






