-- Vehicles Platform Service Schema (baseline)
CREATE SCHEMA IF NOT EXISTS vehicles;

-- Makes
CREATE TABLE IF NOT EXISTS vehicles.make (
  id BIGSERIAL PRIMARY KEY,
  name TEXT NOT NULL
);

-- Models
CREATE TABLE IF NOT EXISTS vehicles.model (
  id BIGSERIAL PRIMARY KEY,
  make_id BIGINT NOT NULL REFERENCES vehicles.make(id) ON DELETE RESTRICT,
  name TEXT NOT NULL
);

-- Model availability by year
CREATE TABLE IF NOT EXISTS vehicles.model_year (
  id BIGSERIAL PRIMARY KEY,
  model_id BIGINT NOT NULL REFERENCES vehicles.model(id) ON DELETE RESTRICT,
  year INTEGER NOT NULL CHECK (year BETWEEN 1950 AND 2100)
);

-- Trims (year-specific)
CREATE TABLE IF NOT EXISTS vehicles.trim (
  id BIGSERIAL PRIMARY KEY,
  model_year_id BIGINT NOT NULL REFERENCES vehicles.model_year(id) ON DELETE RESTRICT,
  name TEXT NOT NULL
);

-- Engines (canonical)
CREATE TABLE IF NOT EXISTS vehicles.engine (
  id BIGSERIAL PRIMARY KEY,
  name TEXT NOT NULL,
  code TEXT NULL,
  displacement_l NUMERIC(3,1) NULL,
  cylinders SMALLINT NULL,
  fuel_type TEXT NULL,
  aspiration TEXT NULL
);

-- Trim to Engine mapping (many-to-many)
CREATE TABLE IF NOT EXISTS vehicles.trim_engine (
  trim_id BIGINT NOT NULL REFERENCES vehicles.trim(id) ON DELETE RESTRICT,
  engine_id BIGINT NOT NULL REFERENCES vehicles.engine(id) ON DELETE RESTRICT,
  PRIMARY KEY (trim_id, engine_id)
);

-- Optional: Transmissions (reserved for future)
CREATE TABLE IF NOT EXISTS vehicles.transmission (
  id BIGSERIAL PRIMARY KEY,
  name TEXT NOT NULL,
  type TEXT NULL,
  gears SMALLINT NULL
);

CREATE TABLE IF NOT EXISTS vehicles.trim_transmission (
  trim_id BIGINT NOT NULL REFERENCES vehicles.trim(id) ON DELETE RESTRICT,
  transmission_id BIGINT NOT NULL REFERENCES vehicles.transmission(id) ON DELETE RESTRICT,
  PRIMARY KEY (trim_id, transmission_id)
);

-- Optional: Performance (reserved for future)
CREATE TABLE IF NOT EXISTS vehicles.performance (
  id BIGSERIAL PRIMARY KEY,
  engine_id BIGINT NULL REFERENCES vehicles.engine(id) ON DELETE SET NULL,
  trim_id BIGINT NULL REFERENCES vehicles.trim(id) ON DELETE SET NULL,
  horsepower NUMERIC(6,2) NULL,
  torque NUMERIC(6,2) NULL,
  top_speed NUMERIC(6,2) NULL,
  zero_to_sixty NUMERIC(4,2) NULL
);

