-- Normalize existing model names in application database
-- - Replace underscores with spaces
-- - Title-case words
-- - Uppercase common acronyms (HD, GT, Z06, etc.)

-- Create helper function to normalize model names
CREATE OR REPLACE FUNCTION normalize_model_name_app(input TEXT)
RETURNS TEXT
LANGUAGE plpgsql
IMMUTABLE
AS $$
DECLARE
  s TEXT;
BEGIN
  IF input IS NULL THEN RETURN NULL; END IF;
  s := input;
  -- underscores to spaces, collapse whitespace, trim
  s := regexp_replace(s, '_+', ' ', 'g');
  s := btrim(regexp_replace(s, '\\s+', ' ', 'g'));
  -- title case baseline
  s := initcap(lower(s));
  -- uppercase common acronyms using word boundaries
  s := regexp_replace(s, '(^|\\s)(Hd)(\\s|$)', '\\1HD\\3', 'gi');
  s := regexp_replace(s, '(^|\\s)(Gt)(\\s|$)', '\\1GT\\3', 'gi');
  s := regexp_replace(s, '(^|\\s)(Gl)(\\s|$)', '\\1GL\\3', 'gi');
  s := regexp_replace(s, '(^|\\s)(Se)(\\s|$)', '\\1SE\\3', 'gi');
  s := regexp_replace(s, '(^|\\s)(Le)(\\s|$)', '\\1LE\\3', 'gi');
  s := regexp_replace(s, '(^|\\s)(Xle)(\\s|$)', '\\1XLE\\3', 'gi');
  s := regexp_replace(s, '(^|\\s)(Rs)(\\s|$)', '\\1RS\\3', 'gi');
  s := regexp_replace(s, '(^|\\s)(Svt)(\\s|$)', '\\1SVT\\3', 'gi');
  s := regexp_replace(s, '(^|\\s)(Xr)(\\s|$)', '\\1XR\\3', 'gi');
  s := regexp_replace(s, '(^|\\s)(St)(\\s|$)', '\\1ST\\3', 'gi');
  s := regexp_replace(s, '(^|\\s)(Fx4)(\\s|$)', '\\1FX4\\3', 'gi');
  s := regexp_replace(s, '(^|\\s)(Trd)(\\s|$)', '\\1TRD\\3', 'gi');
  s := regexp_replace(s, '(^|\\s)(Zr1)(\\s|$)', '\\1ZR1\\3', 'gi');
  s := regexp_replace(s, '(^|\\s)(Z06)(\\s|$)', '\\1Z06\\3', 'gi');
  s := regexp_replace(s, '(^|\\s)(Gti)(\\s|$)', '\\1GTI\\3', 'gi');
  s := regexp_replace(s, '(^|\\s)(Gli)(\\s|$)', '\\1GLI\\3', 'gi');
  s := regexp_replace(s, '(^|\\s)(Si)(\\s|$)', '\\1SI\\3', 'gi');
  s := regexp_replace(s, '(^|\\s)(Ss)(\\s|$)', '\\1SS\\3', 'gi');
  s := regexp_replace(s, '(^|\\s)(Lt)(\\s|$)', '\\1LT\\3', 'gi');
  s := regexp_replace(s, '(^|\\s)(Ltz)(\\s|$)', '\\1LTZ\\3', 'gi');
  s := regexp_replace(s, '(^|\\s)(Rt)(\\s|$)', '\\1RT\\3', 'gi');
  s := regexp_replace(s, '(^|\\s)(Srt)(\\s|$)', '\\1SRT\\3', 'gi');
  s := regexp_replace(s, '(^|\\s)(Sr)(\\s|$)', '\\1SR\\3', 'gi');
  s := regexp_replace(s, '(^|\\s)(Sr5)(\\s|$)', '\\1SR5\\3', 'gi');
  s := regexp_replace(s, '(^|\\s)(Xse)(\\s|$)', '\\1XSE\\3', 'gi');
  s := regexp_replace(s, '(^|\\s)(Sel)(\\s|$)', '\\1SEL\\3', 'gi');
  RETURN s;
END;
$$;

-- Update existing rows in application tables
UPDATE vehicles
SET model = normalize_model_name_app(model)
WHERE model IS NOT NULL AND model <> normalize_model_name_app(model);

UPDATE vin_cache
SET model = normalize_model_name_app(model)
WHERE model IS NOT NULL AND model <> normalize_model_name_app(model);

