-- Community-submitted gas stations with 93 octane
-- Requires admin approval before public visibility

CREATE TABLE IF NOT EXISTS community_stations (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  submitted_by VARCHAR(255) NOT NULL,

  -- Station details
  name VARCHAR(200) NOT NULL,
  address TEXT NOT NULL,
  city VARCHAR(100),
  state VARCHAR(50),
  zip_code VARCHAR(20),
  latitude DECIMAL(10, 8) NOT NULL,
  longitude DECIMAL(11, 8) NOT NULL,
  brand VARCHAR(100),

  -- 93 Octane specifics (core feature)
  has_93_octane BOOLEAN DEFAULT true,
  has_93_octane_ethanol_free BOOLEAN DEFAULT false,
  price_93 DECIMAL(5, 3),

  -- User notes
  notes TEXT,

  -- Approval workflow
  status VARCHAR(20) DEFAULT 'pending' CHECK (status IN ('pending', 'approved', 'rejected')),
  reviewed_by VARCHAR(255),
  reviewed_at TIMESTAMP WITH TIME ZONE,
  rejection_reason TEXT,

  -- Timestamps
  created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);

-- Indexes for common queries
CREATE INDEX IF NOT EXISTS idx_community_stations_status ON community_stations(status);
CREATE INDEX IF NOT EXISTS idx_community_stations_location ON community_stations(latitude, longitude);
CREATE INDEX IF NOT EXISTS idx_community_stations_submitted_by ON community_stations(submitted_by);
CREATE INDEX IF NOT EXISTS idx_community_stations_created_at ON community_stations(created_at DESC);

-- Add trigger for updated_at
DO $$
BEGIN
  IF NOT EXISTS (
    SELECT 1 FROM pg_trigger WHERE tgname = 'update_community_stations_updated_at'
  ) THEN
    CREATE TRIGGER update_community_stations_updated_at
      BEFORE UPDATE ON community_stations
      FOR EACH ROW
      EXECUTE FUNCTION update_updated_at_column();
  END IF;
END;
$$;
