-- Add assignee, due date, and checklist support to kanban cards

-- Add assignee_id to kanban_cards (references profiles)
ALTER TABLE kanban_cards ADD COLUMN IF NOT EXISTS assignee_id UUID REFERENCES profiles(id) ON DELETE SET NULL;

-- Add due_date for SLA/deadline tracking
ALTER TABLE kanban_cards ADD COLUMN IF NOT EXISTS due_date TIMESTAMPTZ;

-- Add priority field
ALTER TABLE kanban_cards ADD COLUMN IF NOT EXISTS priority TEXT CHECK (priority IN ('low', 'medium', 'high', 'urgent')) DEFAULT 'medium';

-- Create checklist items table
CREATE TABLE IF NOT EXISTS kanban_checklist_items (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    card_id UUID NOT NULL REFERENCES kanban_cards(id) ON DELETE CASCADE,
    title TEXT NOT NULL,
    completed BOOLEAN DEFAULT false,
    position INTEGER DEFAULT 0,
    created_at TIMESTAMPTZ DEFAULT now(),
    updated_at TIMESTAMPTZ DEFAULT now()
);

-- Enable RLS on checklist items
ALTER TABLE kanban_checklist_items ENABLE ROW LEVEL SECURITY;

-- Checklist items inherit access from the card's board -> org
CREATE POLICY "Checklist items inherit card access" ON kanban_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 m ON b.org_id = m.org_id
            WHERE c.id = kanban_checklist_items.card_id
            AND m.user_id = auth.uid()
        )
    );

-- Create index for faster lookups
CREATE INDEX IF NOT EXISTS idx_kanban_cards_assignee ON kanban_cards(assignee_id);
CREATE INDEX IF NOT EXISTS idx_kanban_cards_due_date ON kanban_cards(due_date);
CREATE INDEX IF NOT EXISTS idx_checklist_items_card ON kanban_checklist_items(card_id);
