START TRANSACTION;

CREATE TABLE IF NOT EXISTS flashcard_sets (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  title VARCHAR(255) NOT NULL,
  description TEXT NULL,
  status ENUM('active','inactive') NOT NULL DEFAULT 'active',
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  KEY idx_flashcard_sets_title (title),
  KEY idx_flashcard_sets_status (status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS flashcard_set_words (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  set_id BIGINT UNSIGNED NOT NULL,
  word_id BIGINT UNSIGNED NOT NULL,
  order_no INT UNSIGNED NOT NULL DEFAULT 1,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_flashcard_set_word (set_id, word_id),
  KEY idx_flashcard_set_order (set_id, order_no),
  KEY idx_flashcard_word (word_id),
  CONSTRAINT fk_flashcard_set_words_set FOREIGN KEY (set_id)
    REFERENCES flashcard_sets(id) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT fk_flashcard_set_words_word FOREIGN KEY (word_id)
    REFERENCES words(id) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

COMMIT;
