-- Create tablo_access table for managing shared access to tablos
CREATE TABLE IF NOT EXISTS tablo_access (
    id SERIAL PRIMARY KEY,
    tablo_id INTEGER NOT NULL,
    user_id UUID NOT NULL,
    granted_by UUID NOT NULL,
    is_active BOOLEAN DEFAULT TRUE,
    is_admin BOOLEAN DEFAULT FALSE,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    
    -- Foreign key constraint to tablos table
    CONSTRAINT fk_tablo_access_tablo_id 
        FOREIGN KEY (tablo_id) REFERENCES tablos(id) ON DELETE CASCADE,
    
    -- Foreign key constraint to users table (auth.users)
    CONSTRAINT fk_tablo_access_user_id 
        FOREIGN KEY (user_id) REFERENCES auth.users(id) ON DELETE CASCADE,
    
    -- Foreign key constraint to profiles table
    CONSTRAINT fk_tablo_access_user_id_from_profiles 
        FOREIGN KEY (user_id) REFERENCES profiles(id)
);

-- Create indexes for performance
CREATE INDEX IF NOT EXISTS idx_tablo_access_tablo_id ON tablo_access(tablo_id);
CREATE INDEX IF NOT EXISTS idx_tablo_access_user_id ON tablo_access(user_id);

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

-- Policy to allow users to view tablo_access records where they are the user
CREATE POLICY "Users can view their tablo access only if the access is active" ON tablo_access
    FOR SELECT USING (
        user_id = (SELECT auth.uid())
        AND is_active = TRUE
    );
