-- Create submission table for ride model technical specifications
-- This ensures technical specs flow through the submission pipeline without data loss

CREATE TABLE ride_model_submission_technical_specifications (
  id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
  ride_model_submission_id UUID NOT NULL,
  spec_name TEXT NOT NULL,
  spec_value TEXT NOT NULL,
  spec_unit TEXT,
  category TEXT,
  display_order INTEGER DEFAULT 0,
  created_at TIMESTAMPTZ DEFAULT now(),
  
  CONSTRAINT fk_ride_model_submission
    FOREIGN KEY (ride_model_submission_id)
    REFERENCES ride_model_submissions(id)
    ON DELETE CASCADE,
  
  CONSTRAINT unique_ride_model_submission_spec 
    UNIQUE(ride_model_submission_id, spec_name)
);

CREATE INDEX idx_ride_model_submission_specs_submission 
  ON ride_model_submission_technical_specifications(ride_model_submission_id);

-- Enable RLS
ALTER TABLE ride_model_submission_technical_specifications ENABLE ROW LEVEL SECURITY;

-- Moderators can view all submission specs
CREATE POLICY "Moderators can view all ride model submission specs"
  ON ride_model_submission_technical_specifications
  FOR SELECT
  USING (
    is_moderator(auth.uid()) AND 
    ((NOT has_mfa_enabled(auth.uid())) OR has_aal2())
  );

-- Users can view their own submission specs
CREATE POLICY "Users can view their own ride model submission specs"
  ON ride_model_submission_technical_specifications
  FOR SELECT
  USING (
    EXISTS (
      SELECT 1 FROM ride_model_submissions rms
      JOIN content_submissions cs ON cs.id = rms.submission_id
      WHERE rms.id = ride_model_submission_technical_specifications.ride_model_submission_id
      AND cs.user_id = auth.uid()
    )
  );

-- Users can insert their own submission specs
CREATE POLICY "Users can insert their own ride model submission specs"
  ON ride_model_submission_technical_specifications
  FOR INSERT
  WITH CHECK (
    EXISTS (
      SELECT 1 FROM ride_model_submissions rms
      JOIN content_submissions cs ON cs.id = rms.submission_id
      WHERE rms.id = ride_model_submission_technical_specifications.ride_model_submission_id
      AND cs.user_id = auth.uid()
    )
    AND NOT is_user_banned(auth.uid())
  );

-- Moderators can update submission specs
CREATE POLICY "Moderators can update ride model submission specs"
  ON ride_model_submission_technical_specifications
  FOR UPDATE
  USING (
    is_moderator(auth.uid()) AND 
    ((NOT has_mfa_enabled(auth.uid())) OR has_aal2())
  );

-- Moderators can delete submission specs
CREATE POLICY "Moderators can delete ride model submission specs"
  ON ride_model_submission_technical_specifications
  FOR DELETE
  USING (
    is_moderator(auth.uid()) AND 
    ((NOT has_mfa_enabled(auth.uid())) OR has_aal2())
  );

COMMENT ON TABLE ride_model_submission_technical_specifications IS 
  'Stores technical specifications for ride models during moderation - prevents data loss in submission pipeline';