-- Vehicle Database Schema
-- Tables for storing vehicle information: brands, years, models, and engines

-- Table for vehicle brands/manufacturers
CREATE TABLE IF NOT EXISTS brands (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL UNIQUE,
    country TEXT,
    founded_year INTEGER,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);

-- Table for engine specifications
CREATE TABLE IF NOT EXISTS engines (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL,
    displacement_cc REAL,  -- Engine displacement in cubic centimeters
    cylinders INTEGER,     -- Number of cylinders
    fuel_type TEXT CHECK(fuel_type IN ('gasoline', 'diesel', 'electric', 'hybrid', 'other')),
    power_hp INTEGER,      -- Horsepower
    torque_nm INTEGER,     -- Torque in Newton meters
    engine_code TEXT,      -- Manufacturer engine code
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);

-- Table for vehicle models
CREATE TABLE IF NOT EXISTS models (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    brand_id INTEGER NOT NULL,
    name TEXT NOT NULL,
    body_type TEXT CHECK(body_type IN ('sedan', 'hatchback', 'suv', 'truck', 'coupe', 'convertible', 'wagon', 'van', 'other')),
    generation TEXT,       -- Model generation (e.g., MK1, MK2)
    production_start_year INTEGER,
    production_end_year INTEGER,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (brand_id) REFERENCES brands(id)
);

-- Table for years (to link with models)
CREATE TABLE IF NOT EXISTS years (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    year INTEGER NOT NULL UNIQUE,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);

-- Junction table to connect models, years, and engines
CREATE TABLE IF NOT EXISTS model_year_engine (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    model_id INTEGER NOT NULL,
    year_id INTEGER NOT NULL,
    engine_id INTEGER NOT NULL,
    trim_level TEXT,       -- Trim level (e.g., base, luxury, sport)
    drivetrain TEXT CHECK(drivetrain IN ('FWD', 'RWD', 'AWD', '4WD', 'other')),
    transmission TEXT CHECK(transmission IN ('manual', 'automatic', 'CVT', 'other')),
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (model_id) REFERENCES models(id),
    FOREIGN KEY (year_id) REFERENCES years(id),
    FOREIGN KEY (engine_id) REFERENCES engines(id),
    UNIQUE(model_id, year_id, engine_id, trim_level)  -- Prevent duplicate combinations
);

-- Indexes for better performance
CREATE INDEX IF NOT EXISTS idx_models_brand ON models(brand_id);
CREATE INDEX IF NOT EXISTS idx_model_year_engine_model ON model_year_engine(model_id);
CREATE INDEX IF NOT EXISTS idx_model_year_engine_year ON model_year_engine(year_id);
CREATE INDEX IF NOT EXISTS idx_model_year_engine_engine ON model_year_engine(engine_id);