-- Create tablos table
CREATE TABLE IF NOT EXISTS tablos (
    id SERIAL PRIMARY KEY,
    owner_id UUID NOT NULL,
    name VARCHAR(255) NOT NULL,
    image TEXT,
    color VARCHAR(50),
    status VARCHAR(20) NOT NULL DEFAULT 'todo',
    position INTEGER NOT NULL DEFAULT 0,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    deleted_at TIMESTAMP WITH TIME ZONE DEFAULT NULL,
    
    -- Constraint to ensure status is one of the allowed values
    CONSTRAINT tablos_status_check CHECK (status IN ('todo', 'in_progress', 'done'))
);

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

-- Create policy to allow users to see only their own tablos
CREATE POLICY "Users can view tablos they have access to" ON tablos
		FOR SELECT
    TO authenticated
    USING (
        (SELECT auth.uid()) = owner_id
        OR EXISTS (
            SELECT 1 FROM tablo_access WHERE tablo_id = tablos.id AND user_id = (SELECT auth.uid())
        )
    );

-- Create policy to allow users to insert their own tablos
CREATE POLICY "Users can insert own tablos" ON tablos
		FOR INSERT
    TO authenticated
    WITH CHECK ((SELECT auth.uid()) = owner_id);

-- -- Create policy to allow users to update their own tablos
CREATE POLICY "Users can update own tablos" ON tablos
		FOR UPDATE
    TO authenticated
    USING ((SELECT auth.uid()) = owner_id)
    WITH CHECK ((SELECT auth.uid()) = owner_id);