-- Migration: Create lesson_stories pivot table
-- Description: N-N relationship between Lessons and Stories
-- Date: 2026-02-26

CREATE TABLE IF NOT EXISTS `lesson_stories` (
  `id` CHAR(36) NOT NULL PRIMARY KEY,
  `lesson_id` CHAR(36) NOT NULL,
  `story_id` CHAR(36) NOT NULL,
  `display_order` INT DEFAULT 0 COMMENT 'Thứ tự hiển thị story trong lesson',
  `is_required` BOOLEAN DEFAULT TRUE COMMENT 'Story này có bắt buộc hoàn thành không',
  `created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  
  -- Indexes
  INDEX `idx_lesson_id` (`lesson_id`),
  INDEX `idx_story_id` (`story_id`),
  INDEX `idx_display_order` (`display_order`),
  
  -- Unique constraint to prevent duplicate relationships
  UNIQUE KEY `unique_lesson_story` (`lesson_id`, `story_id`),
  
  -- Foreign keys
  CONSTRAINT `fk_lesson_stories_lesson`
    FOREIGN KEY (`lesson_id`)
    REFERENCES `lessons` (`id`)
    ON DELETE CASCADE
    ON UPDATE CASCADE,
    
  CONSTRAINT `fk_lesson_stories_story`
    FOREIGN KEY (`story_id`)
    REFERENCES `stories` (`id`)
    ON DELETE CASCADE
    ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
COMMENT='Pivot table for N-N relationship between Lessons and Stories';
