-- Task comments for kanban cards

CREATE TABLE IF NOT EXISTS kanban_comments (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    card_id UUID NOT NULL REFERENCES kanban_cards(id) ON DELETE CASCADE,
    user_id UUID NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
    content TEXT NOT NULL,
    created_at TIMESTAMPTZ DEFAULT now(),
    updated_at TIMESTAMPTZ DEFAULT now()
);

-- Enable RLS
ALTER TABLE kanban_comments ENABLE ROW LEVEL SECURITY;

-- Comments inherit access from the card's board -> org
CREATE POLICY "Comments inherit card access" ON kanban_comments
    FOR SELECT USING (
        EXISTS (
            SELECT 1 FROM kanban_cards c
            JOIN kanban_columns col ON c.column_id = col.id
            JOIN kanban_boards b ON col.board_id = b.id
            JOIN org_members m ON b.org_id = m.org_id
            WHERE c.id = kanban_comments.card_id
            AND m.user_id = auth.uid()
        )
    );

-- Users can insert their own comments
CREATE POLICY "Users can insert own comments" ON kanban_comments
    FOR INSERT WITH CHECK (
        user_id = auth.uid() AND
        EXISTS (
            SELECT 1 FROM kanban_cards c
            JOIN kanban_columns col ON c.column_id = col.id
            JOIN kanban_boards b ON col.board_id = b.id
            JOIN org_members m ON b.org_id = m.org_id
            WHERE c.id = kanban_comments.card_id
            AND m.user_id = auth.uid()
        )
    );

-- Users can update their own comments
CREATE POLICY "Users can update own comments" ON kanban_comments
    FOR UPDATE USING (user_id = auth.uid());

-- Users can delete their own comments
CREATE POLICY "Users can delete own comments" ON kanban_comments
    FOR DELETE USING (user_id = auth.uid());

-- Index for faster lookups
CREATE INDEX IF NOT EXISTS idx_kanban_comments_card ON kanban_comments(card_id);
CREATE INDEX IF NOT EXISTS idx_kanban_comments_user ON kanban_comments(user_id);
CREATE INDEX IF NOT EXISTS idx_kanban_comments_created ON kanban_comments(created_at DESC);
