/*
  # Create Reels Tables

  1. New Tables
    - `reels`
      - `id` (uuid, primary key)
      - `user_id` (references users)
      - `video_url` (text, required)
      - `thumbnail_url` (text)
      - `caption` (text)
      - `duration` (integer, in seconds)
      - `views` (integer, default 0)
      - `created_at` (timestamp)
      - `updated_at` (timestamp)
    
  2. Security
    - Enable RLS on `reels` table
    - Add policies for CRUD operations
*/

-- Create reels table
CREATE TABLE IF NOT EXISTS reels (
  id SERIAL PRIMARY KEY,
  user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
  video_url TEXT NOT NULL,
  thumbnail_url TEXT,
  caption TEXT,
  duration INTEGER,
  views INTEGER DEFAULT 0,
  created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);

-- Create indexes for better performance
CREATE INDEX IF NOT EXISTS reels_user_id_idx ON reels(user_id);
CREATE INDEX IF NOT EXISTS reels_created_at_idx ON reels(created_at);

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

-- Create policies
CREATE POLICY "Users can view all reels"
  ON reels FOR SELECT
  TO authenticated
  USING (true);

CREATE POLICY "Users can create their own reels"
  ON reels FOR INSERT
  TO authenticated
  WITH CHECK (user_id = auth.uid()::integer);

CREATE POLICY "Users can update their own reels"
  ON reels FOR UPDATE
  TO authenticated
  USING (user_id = auth.uid()::integer);

CREATE POLICY "Users can delete their own reels"
  ON reels FOR DELETE
  TO authenticated
  USING (user_id = auth.uid()::integer);