-- Add description to kanban_cards and create checklist tables

-- Add description column to kanban_cards if not exists
ALTER TABLE kanban_cards ADD COLUMN IF NOT EXISTS description TEXT;

-- Checklist items for kanban cards
CREATE TABLE IF NOT EXISTS checklist_items (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  card_id UUID REFERENCES kanban_cards(id) ON DELETE CASCADE,
  title TEXT NOT NULL,
  completed BOOLEAN DEFAULT false,
  position INTEGER NOT NULL,
  created_at TIMESTAMPTZ DEFAULT now()
);

-- Index for performance
CREATE INDEX IF NOT EXISTS idx_checklist_items_card ON checklist_items(card_id);

-- RLS
ALTER TABLE checklist_items ENABLE ROW LEVEL SECURITY;

-- Checklist items inherit card permissions (via board -> org membership)
CREATE POLICY "Org members can view checklist items" ON checklist_items 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 om ON b.org_id = om.org_id
    WHERE c.id = checklist_items.card_id AND om.user_id = auth.uid()
  ));

CREATE POLICY "Editors can manage checklist items" ON checklist_items FOR ALL
  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 om ON b.org_id = om.org_id
    WHERE c.id = checklist_items.card_id 
    AND om.user_id = auth.uid() 
    AND om.role IN ('owner', 'admin', 'editor')
  ));

-- Enable realtime for checklist items
ALTER PUBLICATION supabase_realtime ADD TABLE checklist_items;
