CREATE TABLE address (
	id INT PRIMARY KEY AUTO_INCREMENT,
	country VARCHAR(128) NOT NULL,
	postCode VARCHAR(16) NOT NULL,
	city VARCHAR(128) NOT NULL,
	street VARCHAR(128) NOT NULL,
	block VARCHAR(8) NOT NULL,
	flat INT NULL
);

CREATE TABLE people (
	id INT PRIMARY KEY AUTO_INCREMENT,
	name VARCHAR(128) NOT NULL,
	surname VARCHAR(128) NOT NULL,
	address INT NOT NULL,
	FOREIGN KEY (address) REFERENCES address(id)
);

CREATE TABLE users (
	id INT PRIMARY KEY AUTO_INCREMENT,
	username VARCHAR(32) NOT NULL,
	displayName VARCHAR(32) NOT NULL,
	password VARCHAR(256) NOT NULL,
	person INT NOT NULL,
	FOREIGN KEY (person) REFERENCES people(id),
	isAdmin BOOLEAN NOT NULL DEFAULT false
);

CREATE TABLE warehouse (
	id VARCHAR(16) PRIMARY KEY,
	displayName VARCHAR(255) NOT NULL,
	address INT NULL,
	FOREIGN KEY (address) REFERENCES address(id),
	owner INT NOT NULL,
	FOREIGN KEY (owner) REFERENCES people(id)
);
CREATE TABLE shelf (
	id INT PRIMARY KEY AUTO_INCREMENT,
	name VARCHAR(8) NOT NULL,
	warehouseId VARCHAR(16) NOT NULL,
	FOREIGN KEY (warehouseId) REFERENCES warehouse(id)
);

CREATE TABLE states (
	id INT AUTO_INCREMENT PRIMARY KEY,
	name VARCHAR(64) NOT NULL
);

INSERT INTO states VALUES 
	(1, "Unknown"),
	(2, "Working"),
	(3, "Broken");

CREATE TABLE item (
	id INT PRIMARY KEY AUTO_INCREMENT,
	storageShelf INT NULL,
	FOREIGN KEY (storageShelf) REFERENCES shelf(id),
	name VARCHAR(64) NOT NULL,
	description TEXT NULL,
	owner INT NOT NULL,
	FOREIGN KEY (owner) REFERENCES people(id),
	state INT NOT NULL DEFAULT 1,
	FOREIGN KEY (state) REFERENCES states(id)
);

CREATE TABLE exchanges (
	id INT PRIMARY KEY AUTO_INCREMENT,
	itemId INT NOT NULL,
	FOREIGN KEY (itemId) REFERENCES item(id),
	previousOwner INT NOT NULL,
	FOREIGN KEY (previousOwner) REFERENCES people(id),
	newOwner INT NOT NULL,
	FOREIGN KEY (newOwner) REFERENCES people(id),
	time DATE NULL DEFAULT CURRENT_DATE()
);

CREATE TABLE moves (
	id INT PRIMARY KEY AUTO_INCREMENT,
	itemId INT NOT NULL,
	FOREIGN KEY (itemId) REFERENCES item(id),
	previousLocation INT NOT NULL,
	FOREIGN KEY (previousLocation) REFERENCES shelf(id),
	newLocation INT NOT NULL,
	FOREIGN KEY (newLocation) REFERENCES shelf(id),
	time DATE NULL DEFAULT CURRENT_DATE()
);

CREATE TABLE loans (
	id INT PRIMARY KEY AUTO_INCREMENT,
	itemId INT NOT NULL,
	FOREIGN KEY (itemId) REFERENCES item(id),
	timeLoaned DATE NOT NULL DEFAULT CURRENT_DATE(),
	timeReturned DATE NULL,
	loanerId INT NOT NULL,
	FOREIGN KEY (loanerId) REFERENCES people(id)
);


