-- Create tablo_invitations table
CREATE TABLE IF NOT EXISTS tablo_invitations (
    id SERIAL PRIMARY KEY,
    tablo_id INTEGER NOT NULL,
    invited_email VARCHAR(255) NOT NULL,
    invited_by UUID NOT NULL,
    status VARCHAR(20) NOT NULL DEFAULT 'pending',
    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    
    -- Foreign key constraint to tablos table
    CONSTRAINT fk_tablo_invitations_tablo_id 
        FOREIGN KEY (tablo_id) REFERENCES tablos(id) ON DELETE CASCADE,
    
    -- Constraint to ensure status is one of the allowed values
    CONSTRAINT tablo_invitations_status_check 
        CHECK (status IN ('pending', 'accepted', 'declined')),
    
    -- Unique constraint to prevent duplicate invitations
    CONSTRAINT unique_tablo_invitation 
        UNIQUE (tablo_id, invited_email)
);

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

-- Create policy to allow tablo owners to insert invitations
CREATE POLICY "Tablo owners can insert invitations" ON tablo_invitations
    FOR INSERT WITH CHECK (
        auth.uid() = invited_by AND
        EXISTS (
            SELECT 1 FROM tablos 
            WHERE tablos.id = tablo_invitations.tablo_id 
            AND tablos.user_id = auth.uid()
        )
    );

-- Create index for better query performance
CREATE INDEX idx_tablo_invitations_tablo_id ON tablo_invitations(tablo_id);
CREATE INDEX idx_tablo_invitations_invited_email ON tablo_invitations(invited_email); 