-- Persist actual watering execution runs separately from watering plan configuration.

CREATE TABLE IF NOT EXISTS watering_runs (
  id SERIAL PRIMARY KEY,
  user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
  plan_id INTEGER REFERENCES watering_plans(id) ON DELETE SET NULL,
  property_id INTEGER NOT NULL REFERENCES properties(id) ON DELETE CASCADE,
  run_date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  notes TEXT,
  total_duration_minutes DECIMAL(10,2) DEFAULT 0,
  total_coverage_sqft DECIMAL(12,2) DEFAULT 0,
  total_estimated_gallons DECIMAL(12,2) DEFAULT 0,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE IF NOT EXISTS watering_run_points (
  id SERIAL PRIMARY KEY,
  run_id INTEGER NOT NULL REFERENCES watering_runs(id) ON DELETE CASCADE,
  plan_point_id INTEGER REFERENCES watering_plan_points(id) ON DELETE SET NULL,
  sequence INTEGER NOT NULL,
  lat DECIMAL(10,8),
  lng DECIMAL(11,8),
  sprinkler_mount VARCHAR(20),
  sprinkler_head_type VARCHAR(30),
  sprinkler_gpm DECIMAL(8,2),
  sprinkler_throw_feet DECIMAL(8,2),
  sprinkler_degrees INTEGER,
  sprinkler_length_feet DECIMAL(8,2),
  sprinkler_width_feet DECIMAL(8,2),
  coverage_sqft DECIMAL(10,2),
  sprinkler_heading_degrees INTEGER,
  equipment_id INTEGER REFERENCES user_equipment(id) ON DELETE SET NULL,
  equipment_name VARCHAR(255),
  actual_duration_minutes DECIMAL(10,2) DEFAULT 0,
  actual_gpm DECIMAL(8,2),
  estimated_gallons DECIMAL(12,2) DEFAULT 0,
  notes TEXT,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE INDEX IF NOT EXISTS idx_watering_runs_user_date
  ON watering_runs(user_id, run_date DESC);

CREATE INDEX IF NOT EXISTS idx_watering_runs_property_date
  ON watering_runs(property_id, run_date DESC);

CREATE INDEX IF NOT EXISTS idx_watering_run_points_run
  ON watering_run_points(run_id);
