-- Add new dropdown fields to vehicles table
ALTER TABLE vehicles ADD COLUMN IF NOT EXISTS engine VARCHAR(100);
ALTER TABLE vehicles ADD COLUMN IF NOT EXISTS transmission VARCHAR(100);
ALTER TABLE vehicles ADD COLUMN IF NOT EXISTS trim_level VARCHAR(100);
ALTER TABLE vehicles ADD COLUMN IF NOT EXISTS drive_type VARCHAR(50);
ALTER TABLE vehicles ADD COLUMN IF NOT EXISTS fuel_type VARCHAR(50);

-- Create indexes for new fields for potential future searches
CREATE INDEX IF NOT EXISTS idx_vehicles_make ON vehicles(make);
CREATE INDEX IF NOT EXISTS idx_vehicles_model ON vehicles(model);
CREATE INDEX IF NOT EXISTS idx_vehicles_engine ON vehicles(engine);
CREATE INDEX IF NOT EXISTS idx_vehicles_transmission ON vehicles(transmission);
CREATE INDEX IF NOT EXISTS idx_vehicles_trim_level ON vehicles(trim_level);

-- Create dropdown cache table for performance optimization
CREATE TABLE IF NOT EXISTS vehicle_dropdown_cache (
  cache_key VARCHAR(255) PRIMARY KEY,
  data JSONB NOT NULL,
  expires_at TIMESTAMP WITH TIME ZONE NOT NULL,
  created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);

-- Create index on expiry for cleanup tasks
CREATE INDEX IF NOT EXISTS idx_dropdown_cache_expires_at ON vehicle_dropdown_cache(expires_at);

-- Create trigger for updating updated_at on dropdown cache
-- Create trigger to maintain updated_at on vehicle_dropdown_cache
-- Use DROP IF EXISTS and CREATE to handle re-runs safely
DROP TRIGGER IF EXISTS update_dropdown_cache_updated_at ON vehicle_dropdown_cache;
CREATE TRIGGER update_dropdown_cache_updated_at
  BEFORE UPDATE ON vehicle_dropdown_cache
  FOR EACH ROW
  EXECUTE FUNCTION update_updated_at_column();

-- Add comments for documentation
COMMENT ON COLUMN vehicles.engine IS 'Engine configuration from NHTSA vPIC API';
COMMENT ON COLUMN vehicles.transmission IS 'Transmission style from NHTSA vPIC API';
COMMENT ON COLUMN vehicles.trim_level IS 'Trim level from NHTSA vPIC API';
COMMENT ON COLUMN vehicles.drive_type IS 'Drive type (FWD, RWD, AWD, 4WD)';
COMMENT ON COLUMN vehicles.fuel_type IS 'Primary fuel type';
COMMENT ON TABLE vehicle_dropdown_cache IS 'Cache for dropdown data from NHTSA vPIC API';
