-- Minimal seed data for testing dropdown hierarchy
INSERT INTO vehicles.make (name) VALUES ('Honda') ON CONFLICT DO NOTHING;
INSERT INTO vehicles.make (name) VALUES ('Toyota') ON CONFLICT DO NOTHING;

-- Resolve make ids
WITH m AS (
  SELECT id FROM vehicles.make WHERE lower(name) = lower('Honda')
)
INSERT INTO vehicles.model (make_id, name)
SELECT m.id, 'Civic' FROM m
ON CONFLICT DO NOTHING;

WITH m AS (
  SELECT id FROM vehicles.make WHERE lower(name) = lower('Toyota')
)
INSERT INTO vehicles.model (make_id, name)
SELECT m.id, 'Corolla' FROM m
ON CONFLICT DO NOTHING;

-- Model years
WITH mo AS (
  SELECT id FROM vehicles.model WHERE lower(name) = lower('Civic')
)
INSERT INTO vehicles.model_year (model_id, year)
SELECT mo.id, 2024 FROM mo ON CONFLICT DO NOTHING;

WITH mo AS (
  SELECT id FROM vehicles.model WHERE lower(name) = lower('Corolla')
)
INSERT INTO vehicles.model_year (model_id, year)
SELECT mo.id, 2024 FROM mo ON CONFLICT DO NOTHING;

-- Trims
WITH my AS (
  SELECT my.id FROM vehicles.model_year my
  JOIN vehicles.model mo ON mo.id = my.model_id
  WHERE lower(mo.name) = lower('Civic') AND my.year = 2024
)
INSERT INTO vehicles.trim (model_year_id, name)
SELECT my.id, 'LX' FROM my ON CONFLICT DO NOTHING;

WITH my AS (
  SELECT my.id FROM vehicles.model_year my
  JOIN vehicles.model mo ON mo.id = my.model_id
  WHERE lower(mo.name) = lower('Corolla') AND my.year = 2024
)
INSERT INTO vehicles.trim (model_year_id, name)
SELECT my.id, 'LE' FROM my ON CONFLICT DO NOTHING;

-- Engines
INSERT INTO vehicles.engine (name, code, displacement_l, cylinders, fuel_type, aspiration)
VALUES ('2.0L I4', 'K20', 2.0, 4, 'Gasoline', 'NA')
ON CONFLICT DO NOTHING;

INSERT INTO vehicles.engine (name, code, displacement_l, cylinders, fuel_type, aspiration)
VALUES ('2.0L I4', 'M20', 2.0, 4, 'Gasoline', 'NA')
ON CONFLICT DO NOTHING;

-- Map engines to trims
WITH t AS (
  SELECT t.id AS trim_id, e.id AS engine_id
  FROM vehicles.trim t
  JOIN vehicles.model_year my ON my.id = t.model_year_id AND my.year = 2024
  JOIN vehicles.model mo ON mo.id = my.model_id
  JOIN vehicles.make ma ON ma.id = mo.make_id
  JOIN vehicles.engine e ON e.code IN ('K20','M20')
  WHERE lower(ma.name) = lower('Honda') AND lower(mo.name) = lower('Civic') AND lower(t.name) = lower('LX')
)
INSERT INTO vehicles.trim_engine (trim_id, engine_id)
SELECT trim_id, engine_id FROM t ON CONFLICT DO NOTHING;
