-- telemetry_collector: INSERT … ON CONFLICT vyžaduje UNIQUE/PK odpovídající cíli konfliktu.
-- Stejná třída problému jako u market_interval_price (V032): DB bez primárních klíčů z V001.
-- Před ADD PK na hypertable voláme opravu katalogu chunků z V032 (funkce vytvořená tam).

SELECT ems._repair_ts_orphan_chunk_rows('ems', 'telemetry_inverter');

DO $$
BEGIN
  IF EXISTS (
    SELECT 1 FROM pg_catalog.pg_class r
    JOIN pg_catalog.pg_namespace n ON n.oid = r.relnamespace
    WHERE n.nspname = 'ems' AND r.relname = 'telemetry_inverter' AND r.relkind = 'r'
  ) AND NOT EXISTS (
    SELECT 1 FROM pg_catalog.pg_constraint c
    JOIN pg_catalog.pg_class r ON r.oid = c.conrelid
    JOIN pg_catalog.pg_namespace n ON n.oid = r.relnamespace
    WHERE n.nspname = 'ems' AND r.relname = 'telemetry_inverter' AND c.contype = 'p'
  ) THEN
    ALTER TABLE ems.telemetry_inverter
      ADD CONSTRAINT telemetry_inverter_pkey PRIMARY KEY (inverter_id, measured_at);
  END IF;
END $$;

SELECT ems._repair_ts_orphan_chunk_rows('ems', 'telemetry_ev_charger');

DO $$
BEGIN
  IF EXISTS (
    SELECT 1 FROM pg_catalog.pg_class r
    JOIN pg_catalog.pg_namespace n ON n.oid = r.relnamespace
    WHERE n.nspname = 'ems' AND r.relname = 'telemetry_ev_charger' AND r.relkind = 'r'
  ) AND NOT EXISTS (
    SELECT 1 FROM pg_catalog.pg_constraint c
    JOIN pg_catalog.pg_class r ON r.oid = c.conrelid
    JOIN pg_catalog.pg_namespace n ON n.oid = r.relnamespace
    WHERE n.nspname = 'ems' AND r.relname = 'telemetry_ev_charger' AND c.contype = 'p'
  ) THEN
    ALTER TABLE ems.telemetry_ev_charger
      ADD CONSTRAINT telemetry_ev_charger_pkey PRIMARY KEY (charger_id, connector_id, measured_at);
  END IF;
END $$;

SELECT ems._repair_ts_orphan_chunk_rows('ems', 'telemetry_heat_pump');

DO $$
BEGIN
  IF EXISTS (
    SELECT 1 FROM pg_catalog.pg_class r
    JOIN pg_catalog.pg_namespace n ON n.oid = r.relnamespace
    WHERE n.nspname = 'ems' AND r.relname = 'telemetry_heat_pump' AND r.relkind = 'r'
  ) AND NOT EXISTS (
    SELECT 1 FROM pg_catalog.pg_constraint c
    JOIN pg_catalog.pg_class r ON r.oid = c.conrelid
    JOIN pg_catalog.pg_namespace n ON n.oid = r.relnamespace
    WHERE n.nspname = 'ems' AND r.relname = 'telemetry_heat_pump' AND c.contype = 'p'
  ) THEN
    ALTER TABLE ems.telemetry_heat_pump
      ADD CONSTRAINT telemetry_heat_pump_pkey PRIMARY KEY (heat_pump_id, measured_at);
  END IF;
END $$;

-- Jeden otevřený řádek session na nabíječku (V020); bez indexu spadne ON CONFLICT v telemetry_collector.
CREATE UNIQUE INDEX IF NOT EXISTS uidx_ev_session_charger_open
    ON ems.ev_session (charger_id)
    WHERE session_end IS NULL;

DROP FUNCTION IF EXISTS ems._repair_ts_orphan_chunk_rows(name, name);
