-- Experiment Repetitions
-- This migration creates the experiment repetitions table

-- =============================================
-- 1. EXPERIMENT REPETITIONS TABLE
-- =============================================

CREATE TABLE IF NOT EXISTS public.experiment_repetitions (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    experiment_id UUID NOT NULL REFERENCES public.experiments(id) ON DELETE CASCADE,
    repetition_number INTEGER NOT NULL CHECK (repetition_number > 0),
    status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'in_progress', 'completed', 'cancelled')),
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    created_by UUID NOT NULL REFERENCES public.user_profiles(id),
    
    -- Ensure unique repetition numbers per experiment
    UNIQUE(experiment_id, repetition_number)
);

-- =============================================
-- 2. INDEXES FOR PERFORMANCE
-- =============================================

CREATE INDEX IF NOT EXISTS idx_experiment_repetitions_experiment_id ON public.experiment_repetitions(experiment_id);
CREATE INDEX IF NOT EXISTS idx_experiment_repetitions_created_by ON public.experiment_repetitions(created_by);

-- =============================================
-- 3. TRIGGERS
-- =============================================

-- Create trigger for updated_at on experiment_repetitions
CREATE TRIGGER set_updated_at_experiment_repetitions
    BEFORE UPDATE ON public.experiment_repetitions
    FOR EACH ROW
    EXECUTE FUNCTION public.handle_updated_at();

-- =============================================
-- 4. GRANT PERMISSIONS
-- =============================================

GRANT ALL ON public.experiment_repetitions TO authenticated;

-- =============================================
-- 5. ENABLE ROW LEVEL SECURITY
-- =============================================

ALTER TABLE public.experiment_repetitions ENABLE ROW LEVEL SECURITY;

-- =============================================
-- 6. CREATE RLS POLICIES
-- =============================================

CREATE POLICY "Experiment repetitions are viewable by authenticated users" ON public.experiment_repetitions
    FOR SELECT USING (auth.role() = 'authenticated');

CREATE POLICY "Experiment repetitions are insertable by authenticated users" ON public.experiment_repetitions
    FOR INSERT WITH CHECK (auth.role() = 'authenticated');

CREATE POLICY "Experiment repetitions are updatable by authenticated users" ON public.experiment_repetitions
    FOR UPDATE USING (auth.role() = 'authenticated');

CREATE POLICY "Experiment repetitions are deletable by authenticated users" ON public.experiment_repetitions
    FOR DELETE USING (auth.role() = 'authenticated');



