/*
CREATE DATABASE radegast
    WITH 
    OWNER = postgres
    ENCODING = 'utf8'
    TABLESPACE = pg_default
    CONNECTION LIMIT = -1;
*/

--

CREATE SEQUENCE ID_GENERATOR;


CREATE TABLE APP_USER (
	ID INT8 NOT NULL,
	VERSION INT8 NOT NULL DEFAULT 0,
	DELETED BOOLEAN DEFAULT FALSE,

	EMAIL VARCHAR(250) NOT NULL,
	PASSWORD VARCHAR(500),
	PASSWORD_SALT VARCHAR(250),

	FIRST_NAME VARCHAR(250),
	LAST_NAME VARCHAR(250),

	FACEBOOK_ID VARCHAR(500),
	GOOGLE_ID VARCHAR(500),
	TWITTER_ID VARCHAR(500),
	
	ROLE VARCHAR(100),
	UNIT_ID INT8,

	CONSTRAINT PK_APP_USER PRIMARY KEY(ID)
);

CREATE INDEX APP_USER_EMAIL_IDX ON APP_USER(lower(EMAIL));
CREATE INDEX APP_USER_EMAIL_UNIT_IDX ON APP_USER(lower(EMAIL), UNIT_ID);


CREATE TABLE UNIT (
	ID INT8 NOT NULL,
	VERSION NUMERIC(19,0) NOT NULL DEFAULT 0,
	DELETED BOOLEAN DEFAULT FALSE,

	OWNER_ID INT8 NOT NULL,
	NAME VARCHAR(250),
	ID_NUMBER VARCHAR(100),
	TAX_NUMBER VARCHAR(100),
	
	ADDRESS VARCHAR(500),
	EMAIL VARCHAR(250),
	WEB VARCHAR(250),


	PAYMENT_ACCOUNT VARCHAR(250),
	PAYMENT_ACCOUNT_IBAN VARCHAR(250),

	--SETTINGS:
	TIMEZONE VARCHAR(32),
	LOCALE VARCHAR(10),
	DATE_FORMAT VARCHAR(10),
	CURRENCY_FORMAT VARCHAR(10),
	THOUSAND_DELIMITER VARCHAR(10),
	DECIMAL_DELIMITER VARCHAR(10),

	DECIMAL_PRECISSION NUMERIC(3,0),
	ROUNDING_PRECISSION NUMERIC(3, 0),

	INVOICE_SEQUENCE_TYPE VARCHAR(16),

	CURRENCY VARCHAR(3),
	CURRENCY_SYMBOL VARCHAR(16),
	VAT BOOLEAN,

	EMAIL_SENDER_ADDRESS varchar(200),
	INVOICE_EMAIL_SUBJECT varchar(200),
	EMAIL_SIGNATURE varchar(200),	
	INVOICE_THANK_YOU_NOTE varchar(200), 
	
	INITIALIZED BOOLEAN,
	
	INVOICE_TEMPLATE varchar(250),
	INVOICE_TEMPLATE_LANG varchar(32),	
	
	CONSTRAINT PK_UNIT PRIMARY KEY(ID),
	CONSTRAINT FK_UNIT_APP_USER FOREIGN KEY (OWNER_ID) REFERENCES APP_USER(ID)
);

CREATE UNIQUE INDEX UNIT_OWNER_IDX ON UNIT(OWNER_ID);


CREATE TABLE SECTION (
	ID INT8 NOT NULL,

	NAME VARCHAR,
	
	CONSTRAINT PK_SECTION PRIMARY KEY(ID)
);


CREATE TABLE RATING (
	ID INT8 NOT NULL,
	
	SECTION_ID INT8,
	DEVICE_ID VARCHAR,
	KEY VARCHAR,
	CREATED TIMESTAMP,
	
	RATING INT,
		
	CONSTRAINT PK_RATING PRIMARY KEY(ID),
	CONSTRAINT FK_RATING_SECTION FOREIGN KEY (SECTION_ID) REFERENCES SECTION(ID)
);

CREATE INDEX RATING_SECTION_IDX ON RATING(SECTION_ID);
CREATE INDEX RATING_KEY_IDX ON RATING(KEY);




