-- Manual setup for document sharing table
-- Run this in your Supabase SQL Editor

-- Create document_shares table for tracking document sharing permissions
CREATE TABLE IF NOT EXISTS document_shares (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    document_id UUID NOT NULL REFERENCES documents(id) ON DELETE CASCADE,
    shared_by_user_id TEXT NOT NULL, -- User who shared the document
    shared_with_user_id TEXT NOT NULL, -- User who received access
    active BOOLEAN DEFAULT true, -- Whether the share is currently active
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    
    -- Ensure unique combinations
    UNIQUE(document_id, shared_with_user_id)
);

-- Create indexes for better performance
CREATE INDEX IF NOT EXISTS idx_document_shares_document_id ON document_shares(document_id);
CREATE INDEX IF NOT EXISTS idx_document_shares_shared_with_user_id ON document_shares(shared_with_user_id);
CREATE INDEX IF NOT EXISTS idx_document_shares_active ON document_shares(active);

-- Add comments for documentation
COMMENT ON TABLE document_shares IS 'Tracks document sharing permissions between users';
COMMENT ON COLUMN document_shares.document_id IS 'Reference to the shared document';
COMMENT ON COLUMN document_shares.shared_by_user_id IS 'User ID of the person who shared the document';
COMMENT ON COLUMN document_shares.shared_with_user_id IS 'User ID of the person who received access';
COMMENT ON COLUMN document_shares.active IS 'Whether this share is currently active (can be revoked)';

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

-- RLS Policies for document_shares
-- Users can view shares they created or received
CREATE POLICY "Users can view their document shares" ON document_shares
    FOR SELECT USING (
        auth.uid()::text = shared_by_user_id OR 
        auth.uid()::text = shared_with_user_id
    );

-- Users can create shares for documents they own
CREATE POLICY "Users can create document shares" ON document_shares
    FOR INSERT WITH CHECK (
        auth.uid()::text = shared_by_user_id
    );

-- Users can update shares they created
CREATE POLICY "Users can update their document shares" ON document_shares
    FOR UPDATE USING (
        auth.uid()::text = shared_by_user_id
    );

-- Users can delete shares they created
CREATE POLICY "Users can delete their document shares" ON document_shares
    FOR DELETE USING (
        auth.uid()::text = shared_by_user_id
    );

-- Grant necessary permissions
GRANT ALL ON TABLE document_shares TO postgres, service_role;
GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE document_shares TO authenticated;

-- Verify the table was created
SELECT 'Document sharing table created successfully!' as status;
