-- Phase 1.1: Create ride_coaster_stats table
CREATE TABLE IF NOT EXISTS public.ride_coaster_stats (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  ride_id UUID NOT NULL REFERENCES public.rides(id) ON DELETE CASCADE,
  stat_name TEXT NOT NULL,
  stat_value NUMERIC NOT NULL,
  unit TEXT,
  category TEXT,
  description TEXT,
  display_order INTEGER DEFAULT 0,
  created_at TIMESTAMPTZ DEFAULT NOW(),
  updated_at TIMESTAMPTZ DEFAULT NOW(),
  UNIQUE(ride_id, stat_name)
);

CREATE INDEX IF NOT EXISTS idx_ride_coaster_stats_ride_id ON public.ride_coaster_stats(ride_id);

ALTER TABLE public.ride_coaster_stats ENABLE ROW LEVEL SECURITY;

-- Drop existing policies if they exist
DROP POLICY IF EXISTS "Public read coaster stats" ON public.ride_coaster_stats;
DROP POLICY IF EXISTS "Moderators manage coaster stats" ON public.ride_coaster_stats;

CREATE POLICY "Public read coaster stats"
  ON public.ride_coaster_stats FOR SELECT
  USING (true);

CREATE POLICY "Moderators manage coaster stats"
  ON public.ride_coaster_stats FOR ALL
  USING (is_moderator(auth.uid()));

-- Phase 1.2: Drop technical_specs JSONB from ride_model_versions
ALTER TABLE public.ride_model_versions 
DROP COLUMN IF EXISTS technical_specs;

-- Phase 1.3: Ensure RLS policies on relational tables
ALTER TABLE public.ride_technical_specifications ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.ride_model_technical_specifications ENABLE ROW LEVEL SECURITY;

DROP POLICY IF EXISTS "Public read ride tech specs" ON public.ride_technical_specifications;
DROP POLICY IF EXISTS "Moderators manage ride tech specs" ON public.ride_technical_specifications;
DROP POLICY IF EXISTS "Public read model tech specs" ON public.ride_model_technical_specifications;
DROP POLICY IF EXISTS "Moderators manage model tech specs" ON public.ride_model_technical_specifications;

CREATE POLICY "Public read ride tech specs"
  ON public.ride_technical_specifications FOR SELECT
  USING (true);

CREATE POLICY "Moderators manage ride tech specs"
  ON public.ride_technical_specifications FOR ALL
  USING (is_moderator(auth.uid()));

CREATE POLICY "Public read model tech specs"
  ON public.ride_model_technical_specifications FOR SELECT
  USING (true);

CREATE POLICY "Moderators manage model tech specs"
  ON public.ride_model_technical_specifications FOR ALL
  USING (is_moderator(auth.uid()));