-- Create notes table for user notes functionality
CREATE TABLE IF NOT EXISTS notes (
    id TEXT PRIMARY KEY DEFAULT generate_random_string(24),
    title VARCHAR(255) NOT NULL,
    content TEXT,
    user_id UUID NOT NULL,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    deleted_at TIMESTAMP WITH TIME ZONE DEFAULT NULL,
    
    -- Foreign key constraint to users table (auth.users)
    CONSTRAINT fk_notes_user_id 
        FOREIGN KEY (user_id) REFERENCES auth.users(id) ON DELETE CASCADE
);

-- Create indexes for performance
CREATE INDEX IF NOT EXISTS idx_notes_user_id ON notes(user_id);
CREATE INDEX IF NOT EXISTS idx_notes_deleted_at ON notes(deleted_at);
CREATE INDEX IF NOT EXISTS idx_notes_created_at ON notes(created_at);

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

-- Policy to allow users to view their own notes and public notes
CREATE POLICY "Users can view their own notes and public notes" ON notes
    FOR SELECT 
    TO authenticated, anon
    USING (
        user_id = (SELECT auth.uid()) 
        OR EXISTS (
            SELECT 1 FROM shared_notes 
            WHERE shared_notes.note_id = notes.id 
            AND shared_notes.is_public = TRUE
        )
    );

-- Policy to allow users to insert their own notes
CREATE POLICY "Users can insert their own notes" ON notes
    FOR INSERT 
    TO authenticated
    WITH CHECK (
        user_id = (SELECT auth.uid())
    );

-- Policy to allow users to update their own notes
CREATE POLICY "Users can update their own notes" ON notes
    FOR UPDATE 
    TO authenticated
    USING (
        user_id = (SELECT auth.uid())
    )
    WITH CHECK (
        user_id = (SELECT auth.uid())
    );
    
CREATE POLICY "Users can delete their own notes (soft)" ON notes
    FOR UPDATE
    TO authenticated
    USING (user_id = auth.uid() AND deleted_at IS NULL)
    WITH CHECK (user_id = auth.uid());

-- Policy to allow users to delete their own notes (soft delete)
CREATE POLICY "Users can delete their own notes" ON notes
    FOR DELETE 
    TO authenticated
    USING (
        user_id = (SELECT auth.uid())
    );

-- Add comments to document the table
COMMENT ON TABLE notes IS 
    'User notes with Row Level Security. Users can access their own notes and public notes (marked in shared_notes table)';

COMMENT ON COLUMN notes.id IS 
    'Primary key: random 24-character alphanumeric string';

COMMENT ON COLUMN notes.title IS 
    'Title of the note';

COMMENT ON COLUMN notes.content IS 
    'Content of the note (can be plain text or formatted text)';

COMMENT ON COLUMN notes.user_id IS 
    'Foreign key reference to auth.users.id - owner of the note';

COMMENT ON COLUMN notes.deleted_at IS 
    'Soft delete timestamp - when not NULL, the note is considered deleted';

