-- Create fuel_logs table
CREATE TABLE IF NOT EXISTS fuel_logs (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  user_id VARCHAR(255) NOT NULL,
  vehicle_id UUID NOT NULL,
  date DATE NOT NULL,
  odometer INTEGER NOT NULL,
  gallons DECIMAL(10, 3) NOT NULL,
  price_per_gallon DECIMAL(10, 3) NOT NULL,
  total_cost DECIMAL(10, 2) NOT NULL,
  station VARCHAR(200),
  location VARCHAR(200),
  notes TEXT,
  mpg DECIMAL(10, 2), -- Calculated based on previous log
  created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
  
  CONSTRAINT fk_fuel_logs_vehicle
    FOREIGN KEY (vehicle_id)
    REFERENCES vehicles(id)
    ON DELETE CASCADE
);

-- Create indexes
CREATE INDEX IF NOT EXISTS idx_fuel_logs_user_id ON fuel_logs(user_id);
CREATE INDEX IF NOT EXISTS idx_fuel_logs_vehicle_id ON fuel_logs(vehicle_id);
CREATE INDEX IF NOT EXISTS idx_fuel_logs_date ON fuel_logs(date DESC);
CREATE INDEX IF NOT EXISTS idx_fuel_logs_created_at ON fuel_logs(created_at DESC);

-- Add trigger for updated_at
DROP TRIGGER IF EXISTS update_fuel_logs_updated_at ON fuel_logs;
CREATE TRIGGER update_fuel_logs_updated_at
  BEFORE UPDATE ON fuel_logs
  FOR EACH ROW
  EXECUTE FUNCTION update_updated_at_column();