-- Migration: Add todo_users junction table and migrate from assignedTo
-- Created: 2025-11-24
-- Description: Allows many-to-many relationship between todos and users

-- Create todo_users junction table
CREATE TABLE IF NOT EXISTS todo_users (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    todo_id UUID NOT NULL REFERENCES todos(id) ON DELETE CASCADE,
    user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    assigned_by UUID REFERENCES users(id) ON DELETE SET NULL,
    assigned_at TIMESTAMP NOT NULL DEFAULT NOW(),
    CONSTRAINT todo_user_unique UNIQUE(todo_id, user_id)
);

-- Create indexes for better query performance
CREATE INDEX IF NOT EXISTS idx_todo_users_todo_id ON todo_users(todo_id);
CREATE INDEX IF NOT EXISTS idx_todo_users_user_id ON todo_users(user_id);

-- Migrate existing assignedTo data to todo_users table
INSERT INTO todo_users (todo_id, user_id, assigned_by, assigned_at)
SELECT id, assigned_to, created_by, created_at
FROM todos
WHERE assigned_to IS NOT NULL;

-- Drop the old assigned_to column
ALTER TABLE todos DROP COLUMN IF EXISTS assigned_to;

-- Add comment
COMMENT ON TABLE todo_users IS 'Junction table for many-to-many relationship between todos and users (assigned users)';
