
-- Remove angle_degrees from ride_versions (doesn't exist in rides table)
ALTER TABLE public.ride_versions DROP COLUMN IF EXISTS angle_degrees;

-- Update trigger to remove angle_degrees reference
CREATE OR REPLACE FUNCTION public.create_relational_version()
 RETURNS trigger
 LANGUAGE plpgsql
 SECURITY DEFINER
 SET search_path TO 'public'
AS $function$
DECLARE
  v_version_number integer;
  v_created_by uuid;
  v_change_type version_change_type;
  v_submission_id uuid;
  v_version_table text;
  v_entity_id_col text;
BEGIN
  -- Determine version table name
  v_version_table := TG_TABLE_NAME || '_versions';
  v_entity_id_col := TG_TABLE_NAME || '_id';
  
  -- Get user from session config (set by edge function)
  BEGIN
    v_created_by := current_setting('app.current_user_id', true)::uuid;
  EXCEPTION WHEN OTHERS THEN
    v_created_by := auth.uid();
  END;
  
  -- Get submission ID if available
  BEGIN
    v_submission_id := current_setting('app.submission_id', true)::uuid;
  EXCEPTION WHEN OTHERS THEN
    v_submission_id := NULL;
  END;
  
  -- Determine change type
  IF TG_OP = 'INSERT' THEN
    v_change_type := 'created';
    v_version_number := 1;
  ELSIF TG_OP = 'UPDATE' THEN
    -- Only version if data actually changed (ignore updated_at, view counts, ratings)
    IF (OLD.name, OLD.slug, OLD.description, OLD.status) IS NOT DISTINCT FROM 
       (NEW.name, NEW.slug, NEW.description, NEW.status) THEN
      RETURN NEW;
    END IF;
    
    v_change_type := 'updated';
    
    -- Mark previous version as not current
    EXECUTE format('UPDATE %I SET is_current = false WHERE %I = $1 AND is_current = true',
      v_version_table, v_entity_id_col)
    USING NEW.id;
    
    -- Get next version number
    EXECUTE format('SELECT COALESCE(MAX(version_number), 0) + 1 FROM %I WHERE %I = $1',
      v_version_table, v_entity_id_col)
    INTO v_version_number
    USING NEW.id;
  END IF;
  
  -- Insert version record based on table type
  IF TG_TABLE_NAME = 'parks' THEN
    INSERT INTO public.park_versions (
      park_id, version_number, created_by, change_type, submission_id,
      name, slug, description, park_type, status, location_id, operator_id, property_owner_id,
      opening_date, closing_date, opening_date_precision, closing_date_precision,
      website_url, phone, email, banner_image_url, banner_image_id, card_image_url, card_image_id
    ) VALUES (
      NEW.id, v_version_number, v_created_by, v_change_type, v_submission_id,
      NEW.name, NEW.slug, NEW.description, NEW.park_type, NEW.status, NEW.location_id, NEW.operator_id, NEW.property_owner_id,
      NEW.opening_date, NEW.closing_date, NEW.opening_date_precision, NEW.closing_date_precision,
      NEW.website_url, NEW.phone, NEW.email, NEW.banner_image_url, NEW.banner_image_id, NEW.card_image_url, NEW.card_image_id
    );
    
  ELSIF TG_TABLE_NAME = 'rides' THEN
    -- FIXED: Correctly map ALL fields from rides table to ride_versions table
    INSERT INTO public.ride_versions (
      ride_id, version_number, created_by, change_type, submission_id,
      name, slug, description, category, status, park_id, manufacturer_id, designer_id, ride_model_id,
      opening_date, closing_date, opening_date_precision, closing_date_precision,
      height_requirement_cm, age_requirement, max_speed_kmh, duration_seconds, capacity_per_hour, 
      gforce_max, inversions_count, length_meters, height_meters, drop_meters,
      banner_image_url, banner_image_id, card_image_url, card_image_id, image_url,
      ride_sub_type, coaster_type, seating_type, intensity_level,
      track_material, support_material, propulsion_method,
      water_depth_cm, splash_height_meters, wetness_level, flume_type, boat_capacity,
      theme_name, story_description, show_duration_seconds, animatronics_count, projection_type, ride_system, scenes_count,
      rotation_type, motion_pattern, platform_count, swing_angle_degrees, rotation_speed_rpm, arm_length_meters, max_height_reached_meters,
      min_age, max_age, educational_theme, character_theme,
      transport_type, route_length_meters, stations_count, vehicle_capacity, vehicles_count, round_trip_duration_seconds
    ) VALUES (
      NEW.id, v_version_number, v_created_by, v_change_type, v_submission_id,
      NEW.name, NEW.slug, NEW.description, NEW.category, NEW.status, NEW.park_id, NEW.manufacturer_id, NEW.designer_id, NEW.ride_model_id,
      NEW.opening_date, NEW.closing_date, NEW.opening_date_precision, NEW.closing_date_precision,
      NEW.height_requirement, NEW.age_requirement, NEW.max_speed_kmh, NEW.duration_seconds, NEW.capacity_per_hour,
      NEW.max_g_force, NEW.inversions, NEW.length_meters, NEW.max_height_meters, NEW.drop_height_meters,
      NEW.banner_image_url, NEW.banner_image_id, NEW.card_image_url, NEW.card_image_id, NEW.image_url,
      NEW.ride_sub_type, NEW.coaster_type, NEW.seating_type, NEW.intensity_level,
      NEW.track_material, NEW.support_material, NEW.propulsion_method,
      NEW.water_depth_cm, NEW.splash_height_meters, NEW.wetness_level, NEW.flume_type, NEW.boat_capacity,
      NEW.theme_name, NEW.story_description, NEW.show_duration_seconds, NEW.animatronics_count, NEW.projection_type, NEW.ride_system, NEW.scenes_count,
      NEW.rotation_type, NEW.motion_pattern, NEW.platform_count, NEW.swing_angle_degrees, NEW.rotation_speed_rpm, NEW.arm_length_meters, NEW.max_height_reached_meters,
      NEW.min_age, NEW.max_age, NEW.educational_theme, NEW.character_theme,
      NEW.transport_type, NEW.route_length_meters, NEW.stations_count, NEW.vehicle_capacity, NEW.vehicles_count, NEW.round_trip_duration_seconds
    );
    
  ELSIF TG_TABLE_NAME = 'companies' THEN
    INSERT INTO public.company_versions (
      company_id, version_number, created_by, change_type, submission_id,
      name, slug, description, company_type, person_type, founded_year, founded_date, founded_date_precision,
      headquarters_location, website_url, logo_url, banner_image_url, banner_image_id, card_image_url, card_image_id
    ) VALUES (
      NEW.id, v_version_number, v_created_by, v_change_type, v_submission_id,
      NEW.name, NEW.slug, NEW.description, NEW.company_type, NEW.person_type, NEW.founded_year, NEW.founded_date, NEW.founded_date_precision,
      NEW.headquarters_location, NEW.website_url, NEW.logo_url, NEW.banner_image_url, NEW.banner_image_id, NEW.card_image_url, NEW.card_image_id
    );
    
  ELSIF TG_TABLE_NAME = 'ride_models' THEN
    INSERT INTO public.ride_model_versions (
      ride_model_id, version_number, created_by, change_type, submission_id,
      name, slug, manufacturer_id, category, description
    ) VALUES (
      NEW.id, v_version_number, v_created_by, v_change_type, v_submission_id,
      NEW.name, NEW.slug, NEW.manufacturer_id, NEW.category, NEW.description
    );
  END IF;
  
  RETURN NEW;
END;
$function$;

COMMENT ON FUNCTION public.create_relational_version() IS 'Universal versioning trigger - PRODUCTION READY: Correctly maps all ride fields from rides table to ride_versions table with proper field name conversions (height_requirement->height_requirement_cm, max_g_force->gforce_max, inversions->inversions_count, max_height_meters->height_meters, drop_height_meters->drop_meters). All entities now properly versioned with relational structure, no JSONB violations.';
