-- Database Schema (Supabase)
-- Recreate the sessions table fully to support user_ids safely
DROP TABLE IF EXISTS public.sessions;

-- Enable UUIDs if not already available
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    user_id UUID NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
    title TEXT NOT NULL,
    full_text TEXT NOT NULL,
    voice_used TEXT NOT NULL,
    lang_code TEXT DEFAULT 'a' NOT NULL,
    audio_url TEXT NOT NULL,
    duration_seconds INTEGER NOT NULL,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Enable RLS (Row Level Security)
ALTER TABLE public.sessions ENABLE ROW LEVEL SECURITY;

-- Policy to allow users to ONLY see their own sessions
CREATE POLICY "Enable read access for user's own sessions" ON public.sessions 
FOR SELECT USING (auth.uid() = user_id);

-- Policy to allow users to ONLY insert their own sessions
CREATE POLICY "Enable insert access for authenticated users" ON public.sessions 
FOR INSERT WITH CHECK (auth.uid() = user_id);

-- Policy to allow users to ONLY update their own sessions
CREATE POLICY "Enable update access for user's own sessions" ON public.sessions 
FOR UPDATE USING (auth.uid() = user_id);

-- Policy to allow users to ONLY delete their own sessions
CREATE POLICY "Enable delete access for user's own sessions" ON public.sessions 
FOR DELETE USING (auth.uid() = user_id);

-- Storage Buckets Configuration
-- Insert a new public bucket
INSERT INTO storage.buckets (id, name, public) 
VALUES ('audio-files', 'audio-files', true)
ON CONFLICT (id) DO NOTHING;

-- Allows anyone to view/read objects in the bucket
DROP POLICY IF EXISTS "Public Access" ON storage.objects;
CREATE POLICY "Public Access" 
ON storage.objects FOR SELECT 
USING ( bucket_id = 'audio-files' );

-- Allows anon uploads
DROP POLICY IF EXISTS "Public Uploads" ON storage.objects;
CREATE POLICY "Public Uploads" 
ON storage.objects FOR INSERT 
WITH CHECK ( bucket_id = 'audio-files' );
