-- Experiments Tracking Table
CREATE TABLE IF NOT EXISTS experiments (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  name TEXT NOT NULL,
  description TEXT,
  type TEXT NOT NULL CHECK (type IN ('pricing', 'advertising', 'content', 'promotion')),
  status TEXT NOT NULL DEFAULT 'planned' CHECK (status IN ('planned', 'active', 'completed', 'paused')),
  
  -- ASIN targeting
  asins TEXT[] NOT NULL DEFAULT '{}',
  marketplace TEXT NOT NULL,
  
  -- Timing
  start_date DATE NOT NULL,
  end_date DATE,
  created_at TIMESTAMPTZ DEFAULT NOW(),
  updated_at TIMESTAMPTZ DEFAULT NOW(),
  
  -- Hypothesis & Goals
  hypothesis TEXT,
  primary_metric TEXT NOT NULL DEFAULT 'units',
  target_lift_percent NUMERIC,
  
  -- Results (auto-calculated)
  baseline_units NUMERIC,
  baseline_revenue NUMERIC,
  experiment_units NUMERIC,
  experiment_revenue NUMERIC,
  actual_lift_percent NUMERIC,
  statistical_significance NUMERIC,
  
  -- Notes
  learnings TEXT,
  owner TEXT
);

-- Indexes for performance
CREATE INDEX idx_experiments_status ON experiments(status);
CREATE INDEX idx_experiments_marketplace ON experiments(marketplace);
CREATE INDEX idx_experiments_type ON experiments(type);
CREATE INDEX idx_experiments_dates ON experiments(start_date, end_date);
CREATE INDEX idx_experiments_asins ON experiments USING GIN(asins);

-- Updated_at trigger
CREATE OR REPLACE FUNCTION update_updated_at_column()
RETURNS TRIGGER AS $$
BEGIN
  NEW.updated_at = NOW();
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER update_experiments_updated_at
  BEFORE UPDATE ON experiments
  FOR EACH ROW
  EXECUTE FUNCTION update_updated_at_column();

-- RLS Policies (optional - enable if you need row-level security)
-- ALTER TABLE experiments ENABLE ROW LEVEL SECURITY;
