-- Create videos table
CREATE TABLE `nizika_nico`.`videos` ( `id` BIGINT NOT NULL AUTO_INCREMENT , `code` VARCHAR(16) NOT NULL COMMENT '動画 Id.' , `title` VARCHAR(256) NOT NULL COMMENT '動画タイトル' , `description` TEXT NOT NULL COMMENT '概要欄' , `uploaded_at` DATETIME NOT NULL COMMENT '投稿日時' , `deleted_at` DATETIME NULL DEFAULT NULL COMMENT '削除日時' , PRIMARY KEY (`id`)) ENGINE = InnoDB COMMENT = '動画';
ALTER TABLE `videos` ADD UNIQUE(`code`);

-- Create tags table
CREATE TABLE `nizika_nico`.`tags` ( `id` BIGINT NOT NULL AUTO_INCREMENT , `name` VARCHAR(64) NOT NULL COMMENT 'タグ名' , PRIMARY KEY (`id`)) ENGINE = InnoDB COMMENT = 'タグ';
ALTER TABLE `tags` ADD UNIQUE(`name`);

-- Create video_tags table
CREATE TABLE `nizika_nico`.`video_tags` ( `id` BIGINT NOT NULL AUTO_INCREMENT , `video_id` BIGINT NOT NULL COMMENT '動画 Id.' , `tag_id` BIGINT NOT NULL COMMENT 'タグ Id.' , `tagged_at` DATE NOT NULL COMMENT 'タグがつけられた日' , `untagged_at` DATE NULL COMMENT 'タグが外された日' , PRIMARY KEY (`id`)) ENGINE = InnoDB COMMENT = '動画とタグの関係';
ALTER TABLE `video_tags` ADD INDEX(`video_id`);
ALTER TABLE `video_tags` ADD FOREIGN KEY (`video_id`) REFERENCES `videos`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE `video_tags` ADD INDEX(`tag_id`);
ALTER TABLE `video_tags` ADD FOREIGN KEY (`tag_id`) REFERENCES `tags`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;

-- Create users table
CREATE TABLE `nizika_nico`.`users` ( `id` BIGINT NOT NULL AUTO_INCREMENT , `code` VARCHAR(64) NOT NULL COMMENT 'ユーザ・コード' , PRIMARY KEY (`id`)) ENGINE = InnoDB COMMENT = 'ユーザ';
ALTER TABLE `users` ADD UNIQUE(`code`);

-- Create comments table
CREATE TABLE `nizika_nico`.`comments` ( `id` BIGINT NOT NULL AUTO_INCREMENT , `video_id` BIGINT NOT NULL COMMENT '動画 Id.' , `comment_no` INT NOT NULL COMMENT 'コメ番' , `user_id` BIGINT NOT NULL COMMENT 'ユーザ Id.' , `content` VARCHAR(256) NOT NULL COMMENT '内容' , `posted_at` DATETIME NOT NULL COMMENT '投稿日時' , `nico_count` INT NOT NULL DEFAULT '0' COMMENT 'ニコる回数' , PRIMARY KEY (`id`)) ENGINE = InnoDB COMMENT = 'コメント';
ALTER TABLE `comments` ADD INDEX(`video_id`);
ALTER TABLE `comments` ADD FOREIGN KEY (`video_id`) REFERENCES `videos`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE `comments` ADD INDEX(`user_id`);
ALTER TABLE `comments` ADD FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE `comments` ADD UNIQUE(`video_id`, `comment_no`);

-- Create video_histories table
CREATE TABLE `nizika_nico`.`video_histories` ( `id` BIGINT NOT NULL AUTO_INCREMENT , `video_id` BIGINT NOT NULL COMMENT '動画 Id.' , `fetched_at` DATE NOT NULL COMMENT '取得日' , `views_count` INT NOT NULL COMMENT '再生回数' , PRIMARY KEY (`id`)) ENGINE = InnoDB COMMENT = '動画情報推移';
ALTER TABLE `video_histories` ADD INDEX(`video_id`);
ALTER TABLE `video_histories` ADD FOREIGN KEY (`video_id`) REFERENCES `videos`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE `video_histories` ADD UNIQUE(`video_id`, `fetched_at`);
