-- Multi-conversation Odin: conversations table + conversation_id on messages.

CREATE TABLE `ai_conversations` (
  `id` INTEGER NOT NULL AUTO_INCREMENT,
  `user_id` INTEGER NOT NULL,
  `title` VARCHAR(255) NOT NULL,
  `created_at` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
  `updated_at` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
  PRIMARY KEY (`id`),
  INDEX `idx_ai_conv_user` (`user_id`, `id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

ALTER TABLE `ai_chat_messages`
  ADD COLUMN `conversation_id` INTEGER NULL AFTER `user_id`;

-- Backfill: one conversation per user who has messages ("keep as first conversation").
INSERT INTO `ai_conversations` (`user_id`, `title`, `created_at`, `updated_at`)
SELECT `user_id`, 'Konverzace', NOW(), NOW()
FROM `ai_chat_messages`
GROUP BY `user_id`;

UPDATE `ai_chat_messages` m
JOIN `ai_conversations` c ON c.`user_id` = m.`user_id`
SET m.`conversation_id` = c.`id`;

-- Enforce: drop old per-user index, NOT NULL, FK (cascade), per-conversation index.
ALTER TABLE `ai_chat_messages`
  DROP INDEX `idx_ai_chat_user`,
  MODIFY `conversation_id` INTEGER NOT NULL,
  ADD CONSTRAINT `fk_ai_chat_conv` FOREIGN KEY (`conversation_id`)
    REFERENCES `ai_conversations`(`id`) ON DELETE CASCADE,
  ADD INDEX `idx_ai_chat_conv` (`conversation_id`, `id`);
