-- Experiments
-- This migration creates the experiments table

-- =============================================
-- 1. EXPERIMENTS TABLE
-- =============================================

CREATE TABLE IF NOT EXISTS public.experiments (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    experiment_number INTEGER NOT NULL,
    reps_required INTEGER NOT NULL CHECK (reps_required > 0),
    weight_per_repetition_lbs DOUBLE PRECISION NOT NULL DEFAULT 5.0 CHECK (weight_per_repetition_lbs > 0),
    results_status TEXT NOT NULL DEFAULT 'valid' CHECK (results_status IN ('valid', 'invalid')),
    completion_status BOOLEAN NOT NULL DEFAULT false,
    phase_id UUID NOT NULL REFERENCES public.experiment_phases(id) ON DELETE SET NULL,
    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 combination of experiment_number and phase_id
    CONSTRAINT unique_experiment_number_phase UNIQUE (experiment_number, phase_id)
);

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

CREATE INDEX IF NOT EXISTS idx_experiments_phase_id ON public.experiments(phase_id);
CREATE INDEX IF NOT EXISTS idx_experiments_experiment_number ON public.experiments(experiment_number);
CREATE INDEX IF NOT EXISTS idx_experiments_created_by ON public.experiments(created_by);
CREATE INDEX IF NOT EXISTS idx_experiments_id ON public.experiments(id);

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

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

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

GRANT ALL ON public.experiments TO authenticated;

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

ALTER TABLE public.experiments ENABLE ROW LEVEL SECURITY;

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

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

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

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

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

