
CREATE TABLE IF NOT EXISTS sites (
  id VARCHAR(64) PRIMARY KEY,
  name VARCHAR(255) NULL,
  gps_lat DOUBLE NULL,
  gps_lng DOUBLE NULL,
  timezone VARCHAR(64) DEFAULT 'UTC',
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE IF NOT EXISTS site_settings (
  site_id VARCHAR(64) PRIMARY KEY,
  report_interval_s INT DEFAULT 60,
  thresholds JSON NULL,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  FOREIGN KEY (site_id) REFERENCES sites(id) ON DELETE CASCADE
);

CREATE TABLE IF NOT EXISTS ac_telemetry (
  site_id VARCHAR(64),
  ts DATETIME NOT NULL,
  grid_status VARCHAR(8),
  v_l1 DOUBLE, v_l2 DOUBLE, v_l3 DOUBLE,
  i_l1 DOUBLE, i_l2 DOUBLE, i_l3 DOUBLE,
  freq_hz DOUBLE,
  power_kw DOUBLE,
  energy_kwh_month DOUBLE,
  props JSON NULL,
  INDEX idx_ac_ts (site_id, ts),
  FOREIGN KEY (site_id) REFERENCES sites(id) ON DELETE CASCADE
);

CREATE TABLE IF NOT EXISTS gen_telemetry (
  site_id VARCHAR(64),
  ts DATETIME NOT NULL,
  status VARCHAR(8),
  mode VARCHAR(16),
  fuel_level_pct DOUBLE,
  engine_hours DOUBLE,
  v_l1 DOUBLE, v_l2 DOUBLE, v_l3 DOUBLE,
  i_l1 DOUBLE, i_l2 DOUBLE, i_l3 DOUBLE,
  load_pct DOUBLE,
  alarms JSON NULL,
  props JSON NULL,
  INDEX idx_gen_ts (site_id, ts),
  FOREIGN KEY (site_id) REFERENCES sites(id) ON DELETE CASCADE
);

CREATE TABLE IF NOT EXISTS dc_telemetry (
  site_id VARCHAR(64),
  ts DATETIME NOT NULL,
  voltage_v DOUBLE,
  current_a DOUBLE,
  props JSON NULL,
  INDEX idx_dc_ts (site_id, ts),
  FOREIGN KEY (site_id) REFERENCES sites(id) ON DELETE CASCADE
);

CREATE TABLE IF NOT EXISTS battery_telemetry (
  site_id VARCHAR(64),
  ts DATETIME NOT NULL,
  soc_pct DOUBLE,
  soh_pct DOUBLE,
  voltage_v DOUBLE,
  current_a DOUBLE,
  temp_c DOUBLE,
  props JSON NULL,
  INDEX idx_batt_ts (site_id, ts),
  FOREIGN KEY (site_id) REFERENCES sites(id) ON DELETE CASCADE
);

CREATE TABLE IF NOT EXISTS solar_telemetry (
  site_id VARCHAR(64),
  ts DATETIME NOT NULL,
  voltage_v DOUBLE,
  current_a DOUBLE,
  power_kw DOUBLE,
  energy_kwh_day DOUBLE,
  energy_kwh_month DOUBLE,
  props JSON NULL,
  INDEX idx_solar_ts (site_id, ts),
  FOREIGN KEY (site_id) REFERENCES sites(id) ON DELETE CASCADE
);

CREATE TABLE IF NOT EXISTS shelter_telemetry (
  site_id VARCHAR(64),
  ts DATETIME NOT NULL,
  room_temp_c DOUBLE,
  door VARCHAR(8),
  aircon_status VARCHAR(8),
  gps_lat DOUBLE NULL,
  gps_lng DOUBLE NULL,
  props JSON NULL,
  INDEX idx_shelter_ts (site_id, ts),
  FOREIGN KEY (site_id) REFERENCES sites(id) ON DELETE CASCADE
);

CREATE TABLE IF NOT EXISTS events (
  site_id VARCHAR(64),
  ts DATETIME NOT NULL,
  severity VARCHAR(8),
  code VARCHAR(64),
  message VARCHAR(255),
  value VARCHAR(255) NULL,
  props JSON NULL,
  INDEX idx_events_ts (site_id, ts),
  FOREIGN KEY (site_id) REFERENCES sites(id) ON DELETE CASCADE
);
