-- Create the interests table
CREATE TABLE IF NOT EXISTS interests (
  id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
  student_id UUID NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
  category TEXT NOT NULL,
  item TEXT NOT NULL,
  created_at TIMESTAMP WITH TIME ZONE DEFAULT timezone('utc'::text, now()) NOT NULL,
  updated_at TIMESTAMP WITH TIME ZONE DEFAULT timezone('utc'::text, now()) NOT NULL,
  UNIQUE(student_id, category, item)
);

-- Enable Row Level Security
ALTER TABLE interests ENABLE ROW LEVEL SECURITY;

-- Create policies
CREATE POLICY "Students can view their own interests"
  ON interests FOR SELECT
  USING (auth.uid() = student_id);

CREATE POLICY "Students can insert their own interests"
  ON interests FOR INSERT
  WITH CHECK (auth.uid() = student_id);

CREATE POLICY "Students can update their own interests"
  ON interests FOR UPDATE
  USING (auth.uid() = student_id)
  WITH CHECK (auth.uid() = student_id);

CREATE POLICY "Students can delete their own interests"
  ON interests FOR DELETE
  USING (auth.uid() = student_id);

-- Create indexes
CREATE INDEX interests_student_id_idx ON interests(student_id);
CREATE INDEX interests_category_idx ON interests(category);
CREATE INDEX interests_item_idx ON interests(item);

-- Create function to automatically update updated_at
CREATE OR REPLACE FUNCTION update_updated_at_column()
RETURNS TRIGGER AS $$
BEGIN
  NEW.updated_at = timezone('utc'::text, now());
  RETURN NEW;
END;
$$ language 'plpgsql';

-- Create trigger to automatically update updated_at
CREATE TRIGGER update_interests_updated_at
  BEFORE UPDATE ON interests
  FOR EACH ROW
  EXECUTE FUNCTION update_updated_at_column(); 