-- Create station cache table
CREATE TABLE IF NOT EXISTS station_cache (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  place_id VARCHAR(255) UNIQUE NOT NULL,
  name VARCHAR(255) NOT NULL,
  address TEXT NOT NULL,
  latitude DECIMAL(10, 8) NOT NULL,
  longitude DECIMAL(11, 8) NOT NULL,
  price_regular DECIMAL(10, 2),
  price_premium DECIMAL(10, 2),
  price_diesel DECIMAL(10, 2),
  rating DECIMAL(2, 1),
  photo_url TEXT,
  raw_data JSONB,
  cached_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);

-- Create saved stations table for user favorites
CREATE TABLE IF NOT EXISTS saved_stations (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  user_id VARCHAR(255) NOT NULL,
  place_id VARCHAR(255) NOT NULL,
  nickname VARCHAR(100),
  notes TEXT,
  is_favorite BOOLEAN DEFAULT false,
  created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
  
  CONSTRAINT unique_user_station UNIQUE(user_id, place_id)
);

-- Create indexes
CREATE INDEX idx_station_cache_place_id ON station_cache(place_id);
CREATE INDEX idx_station_cache_location ON station_cache(latitude, longitude);
CREATE INDEX idx_station_cache_cached_at ON station_cache(cached_at);

CREATE INDEX idx_saved_stations_user_id ON saved_stations(user_id);
CREATE INDEX idx_saved_stations_is_favorite ON saved_stations(is_favorite);

-- Add trigger for updated_at
CREATE TRIGGER update_saved_stations_updated_at
  BEFORE UPDATE ON saved_stations
  FOR EACH ROW
  EXECUTE FUNCTION update_updated_at_column();