/* CREATE THE DATABASE FROM SCRATCH */

CREATE database demodb;

USE demodb;

CREATE TABLE `Surveys` (
  `id` int NOT NULL AUTO_INCREMENT,
  `surveyId` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL,
  `description` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
  PRIMARY KEY (`id`),
  UNIQUE KEY `unique_id` (`id`),
  UNIQUE KEY `unique_surveyid` (`surveyId`)
);

CREATE TABLE `Responses` (
  `id` int NOT NULL AUTO_INCREMENT,
  `Q1` int DEFAULT NULL,
  `Q2` int DEFAULT NULL,
  `Q3` int DEFAULT NULL,
  `surveyId` int NOT NULL,
  `responseId` varchar(18) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `startDate` datetime DEFAULT NULL,
  `endDate` datetime DEFAULT NULL,
  `status` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `ipAddress` varchar(45) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `progress` int DEFAULT NULL,
  `duration` int DEFAULT NULL,
  `finished` tinyint(1) DEFAULT NULL,
  `recordedDate` datetime DEFAULT NULL,
  `locationLatitude` decimal(9,6) DEFAULT NULL,
  `locationLongitude` decimal(9,6) DEFAULT NULL,
  `distributionChannel` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `userLanguage` varchar(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `unique_id` (`id`),
  UNIQUE KEY `unique_response_id` (`responseId`),
  KEY `Responses_ibfk_1` (`surveyId`),
  CONSTRAINT `Responses_ibfk_1` FOREIGN KEY (`surveyId`) REFERENCES `Surveys` (`id`)
);

CREATE TABLE `Answers` (
  `id` int NOT NULL AUTO_INCREMENT,
  `surveyId` int NOT NULL,
  `responseId` int NOT NULL,
  `QID` varchar(16) COLLATE utf8mb4_unicode_ci NOT NULL,
  `text` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `value` tinyint DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `unique_survey_response_qid` (`surveyId`,`responseId`,`QID`),
  KEY `surveyId` (`surveyId`),
  KEY `responseId` (`responseId`),
  CONSTRAINT `Answers_ibfk_1` FOREIGN KEY (`surveyId`) REFERENCES `Surveys` (`id`),
  CONSTRAINT `Answers_ibfk_2` FOREIGN KEY (`responseId`) REFERENCES `Responses` (`id`),
  CONSTRAINT `Answers_chk_1` CHECK ((`value` between -(3) and 3))
);

CREATE TABLE `Users` (
  `id` int NOT NULL AUTO_INCREMENT,
  `username` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `password_hash` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `totp_secret` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `role` enum('user','admin') COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'user',
  `created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `username` (`username`)
);

CREATE TABLE Filters (
  id INT NOT NULL AUTO_INCREMENT,
  surveyId VARCHAR(20),
  FilterQuestion INT NOT NULL,
  FilterOption INT NOT NULL,
  Text VARCHAR(128),
  PRIMARY KEY (id)
);