ALTER TABLE IF EXISTS employees DROP CONSTRAINT departments_fk;
ALTER TABLE IF EXISTS employees DROP CONSTRAINT projects_fk;

DROP TABLE IF EXISTS projects CASCADE;
DROP TABLE IF EXISTS departments CASCADE;
DROP TABLE IF EXISTS phones CASCADE;
DROP TABLE IF EXISTS offices CASCADE;
DROP TABLE IF EXISTS employees CASCADE;

CREATE TABLE employees (
  id bigint primary key,
  department_id bigint,
  project_id bigint,
  hired_at date,
  title varchar(255),
  area varchar(255),
  salary decimal
);

CREATE TABLE departments (
  id bigint primary key,
  manager_id bigint references employees(id),
  budget decimal
);

CREATE TABLE projects (
  id bigint primary key,
  department_id bigint references departments(id),
  budget decimal
);

CREATE TABLE phones (
  number varchar(255) primary key,
  employee_id bigint references employees(id)
);

CREATE TABLE offices (
  number varchar(255) primary key,
  employee_id bigint references employees(id)
);

ALTER TABLE employees ADD CONSTRAINT departments_fk FOREIGN KEY (department_id) REFERENCES departments(id);
ALTER TABLE employees ADD CONSTRAINT projects_fk FOREIGN KEY (project_id) REFERENCES projects(id);
CREATE UNIQUE INDEX department_manager_idx on departments(manager_id);
CREATE UNIQUE INDEX employee_phones_idx on phones(employee_id);
CREATE UNIQUE INDEX employee_offices_idx on offices(employee_id);

INSERT INTO departments VALUES (1, NULL, 1000.00);
INSERT INTO departments VALUES (2, NULL, 2000.00);
INSERT INTO departments VALUES (3, NULL, 2000.00);
INSERT INTO departments VALUES (4, NULL, 4000.00);

INSERT INTO projects VALUES (1, 1, 500.00);
INSERT INTO projects VALUES (2, 1, 500.00);
INSERT INTO projects VALUES (3, 3, 1000.00);

\echo '--- insert valid manager'
INSERT INTO employees VALUES(1, 1, 1, '2019-01-01', 'manager', 'area 51', 50000.00);

\echo '--- insert valid employee'
INSERT INTO employees VALUES(2, 1, 2, '2019-01-01', 'engineer', 'area 51', 100000.00);

\echo '--- insert duplicate phone number'
INSERT INTO employees VALUES(3, 1, 3, '2019-01-01', 'manager', 'area 51', 50002.00);

INSERT INTO phones VALUES('+1-555-555-0001', 1);
INSERT INTO phones VALUES('+1-555-555-0002', 2);
INSERT INTO phones VALUES('+1-555-555-0003', 3);
INSERT INTO phones VALUES('+1-555-555-0004', 1);

INSERT INTO offices VALUES('1000', 1);
INSERT INTO offices VALUES('2000', 2);
INSERT INTO offices VALUES('3000', 3);

UPDATE departments SET manager_id = 1 WHERE id = 1;
UPDATE departments SET manager_id = 2 WHERE id = 2;
UPDATE departments SET manager_id = 3 WHERE id = 3;
\echo '--- An employee who is a manager of two different departments'
UPDATE departments SET manager_id = 1 WHERE id = 4;
