-- Creates the webshop DB
--
-- Author: Andreas Zweili
-- 2017-02-03
-- MariaDB 10.0.27

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";

create database if not exists webshopdb;
grant all on webshopdb.* to
    'webshop'@'localhost'
    identified by 'password';
flush privileges;

use webshopdb;
CREATE TABLE if not exists `users` (
  `userId` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `userName` varchar(50) DEFAULT NULL,
  `userFirstname` varchar(50) DEFAULT NULL,
  `userLogin` varchar(50) NOT NULL,
  `userEmail` varchar(60) NOT NULL UNIQUE KEY,
  `userPass` varchar(255) NOT NULL,
  `userIsAdmin` BOOL DEFAULT NULL,
  CONSTRAINT userLoginUnique UNIQUE (userLogin),
  CONSTRAINT userEmailUnique UNIQUE (userEmail)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE if not exists `tags` (
  `tagId` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `text` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE if not exists `quality` (
 `qualityId` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
 `qualityName` varchar(20) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE if not exists `demands` (
  `demandId` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `demandTitle` varchar(50) NOT NULL,
  `demandText` text CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
  `piecesMin` int(11) NOT NULL,
  `piecesMax` int(11) DEFAULT NULL,
  `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, 
  `deliveryDate` date NOT NULL, 
  `qualityId` int(11) NOT NULL,
  `userId` int(11) NOT NULL,
  `tagId` int(11) NULL,
  CONSTRAINT `fk_demands_userId`
        FOREIGN KEY (userId) REFERENCES users (userId),
  CONSTRAINT `fk_demands_qualityId`
        FOREIGN KEY (qualityId) REFERENCES quality (qualityId),
  CONSTRAINT `fk_tagId`
        FOREIGN KEY (tagId) REFERENCES tags (tagId)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE if not exists `offers` (
  `offerId` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `text` text CHARACTER SET utf8 COLLATE utf8_bin,
  `price` float NOT NULL,
  `pieces` int(11) NOT NULL,
  `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, 
  `userId` int(11) NOT NULL,
  `qualityId` int(11) NOT NULL,
  `demandId` int(11) NOT NULL,
   CONSTRAINT `fk_offers_userId`
        FOREIGN KEY (userId) REFERENCES users (userId),
   CONSTRAINT `fk_offers_qualityId`
        FOREIGN KEY (qualityId) REFERENCES quality (qualityId),
   CONSTRAINT `fk_offers_demandId`
        FOREIGN KEY (demandId) REFERENCES demands (demandId)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


