-- Seed specific vehicle combinations requested

-- Ensure makes exist
INSERT INTO vehicles.make (name) VALUES ('GMC') ON CONFLICT DO NOTHING;
INSERT INTO vehicles.make (name) VALUES ('Chevrolet') ON CONFLICT DO NOTHING;

-- Ensure models exist under their makes
WITH m AS (
  SELECT id FROM vehicles.make WHERE lower(name) = lower('GMC')
)
INSERT INTO vehicles.model (make_id, name)
SELECT m.id, 'Sierra 1500' FROM m
ON CONFLICT DO NOTHING;

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

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

WITH mo AS (
  SELECT id FROM vehicles.model WHERE lower(name) = lower('Corvette')
)
INSERT INTO vehicles.model_year (model_id, year)
SELECT mo.id, 2017 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('Sierra 1500') AND my.year = 2023
)
INSERT INTO vehicles.trim (model_year_id, name)
SELECT my.id, 'AT4x' 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('Corvette') AND my.year = 2017
)
INSERT INTO vehicles.trim (model_year_id, name)
SELECT my.id, 'Z06 Convertible' FROM my ON CONFLICT DO NOTHING;

-- Engines (ensure canonical engines exist)
INSERT INTO vehicles.engine (name, code, displacement_l, cylinders, fuel_type, aspiration)
VALUES ('6.2L V8 L87', 'L87', 6.2, 8, 'Gasoline', 'NA')
ON CONFLICT DO NOTHING;

INSERT INTO vehicles.engine (name, code, displacement_l, cylinders, fuel_type, aspiration)
VALUES ('6.2L V8 LT4', 'LT4', 6.2, 8, 'Gasoline', 'SC')
ON CONFLICT DO NOTHING;

-- Map engines to trims
WITH t AS (
  SELECT t.id AS trim_id, t.name AS trim_name, my.year, mo.name AS model_name
  FROM vehicles.trim t
  JOIN vehicles.model_year my ON my.id = t.model_year_id
  JOIN vehicles.model mo ON mo.id = my.model_id
)
INSERT INTO vehicles.trim_engine (trim_id, engine_id)
SELECT t.trim_id, e.id
FROM t
JOIN vehicles.engine e 
  ON (t.model_name = 'Sierra 1500' AND t.year = 2023 AND t.trim_name = 'AT4x' AND e.code = 'L87')
  OR (t.model_name = 'Corvette' AND t.year = 2017 AND t.trim_name = 'Z06 Convertible' AND e.code = 'LT4')
ON CONFLICT DO NOTHING;

