CREATE TABLE IF NOT EXISTS VehicleVersion (
  id BIGINT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(100) NOT NULL,
  constructionType VARCHAR NOT NULL,
  type VARCHAR NOT NULL,
  hasNef BOOLEAN NOT NULL,
  CHECK constructionType IN ('NORMAL', 'HOCHDACH', 'MITTELHOCHDACH'),
  CHECK type IN ('BKTW', 'KTW-B', 'KTW', 'RTW', 'NEF', 'NAH')
);

CREATE TABLE IF NOT EXISTS Vehicle (
  id BIGINT AUTO_INCREMENT PRIMARY KEY,
  version BIGINT NOT NULL,
  status VARCHAR NOT NULL,
  FOREIGN KEY (version) REFERENCES VehicleVersion(id),
  CHECK status IN ('ABGEMELDET', 'FREI_WACHE', 'ZUM_BERUFUNGSORT', 'AM_BERUFUNGSORT', 'ZUM_ZIELORT',
              'AM_ZIELORT', 'FREI_FUNK', 'DELETED')
);

CREATE TABLE IF NOT EXISTS EmployeeVersion (
  id BIGINT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(100) NOT NULL,
  birthday DATE NOT NULL,
  educationLevel VARCHAR NOT NULL,
  isDriver BOOLEAN NOT NULL,
  isPilot BOOLEAN NOT NULL,
  CHECK educationLevel IN ('RS', 'NFS', 'NKV', 'NKA', 'NKI', 'NA')
);

CREATE TABLE IF NOT EXISTS Employee (
  id BIGINT AUTO_INCREMENT PRIMARY KEY,
  version BIGINT NOT NULL,
  FOREIGN KEY (version) REFERENCES EmployeeVersion(id),
);

CREATE TABLE IF NOT EXISTS Registration (
  id BIGINT AUTO_INCREMENT PRIMARY KEY,
  vehicleId BIGINT NOT NULL,
  employeeId BIGINT NOT NULL,
  start TIMESTAMP NOT NULL,
  end TIMESTAMP NOT NULL,
  active BOOLEAN NOT NULL,
  FOREIGN KEY (vehicleId) REFERENCES VehicleVersion(id),
  FOREIGN KEY (employeeId) REFERENCES EmployeeVersion(id),
);

CREATE TABLE IF NOT EXISTS Operation (
  id BIGINT AUTO_INCREMENT PRIMARY KEY,
  opCode VARCHAR(20) NOT NULL,
  severity VARCHAR NOT NULL,
  created TIMESTAMP NOT NULL,
  destination VARCHAR(100) NOT NULL,
  additionalInfo VARCHAR(100),
  status VARCHAR NOT NULL,
  CHECK severity IN ('A', 'B', 'C', 'D', 'E', 'O'),
  CHECK status IN ('ACTIVE', 'COMPLETED', 'CANCELLED')
);

CREATE TABLE IF NOT EXISTS VehicleOperation (
  vehicleId BIGINT NOT NULL,
  operationId BIGINT NOT NULL,
  FOREIGN KEY (vehicleId) REFERENCES VehicleVersion(id),
  FOREIGN KEY (operationId) REFERENCES Operation(id),
  PRIMARY KEY (vehicleId, operationId),
);
