-- V046: Battery slot selection buffers + Deye zero-export mode + solar sell register
--
-- Solver: slot pre-selection eliminates battery micro-cycling.
-- Registers: reg 142 (zero export mode) per-inverter, reg 145 (solar sell) newly managed.

-- ============================================================
-- 1. Slot selection buffers on asset_battery
-- ============================================================

ALTER TABLE ems.asset_battery
  ADD COLUMN IF NOT EXISTS charge_slot_buffer    NUMERIC(3,1) DEFAULT 1.3,
  ADD COLUMN IF NOT EXISTS discharge_slot_buffer NUMERIC(3,1) DEFAULT 1.5;

COMMENT ON COLUMN ems.asset_battery.charge_slot_buffer IS
  'Buffer multiplier for charge slot count over minimum to fill battery (1.0 = exact, 1.3 = 30 % extra). NULL = no slot selection.';
COMMENT ON COLUMN ems.asset_battery.discharge_slot_buffer IS
  'Buffer multiplier for discharge-export slot count over minimum to empty battery (1.0 = exact, 1.5 = 50 % extra). NULL = no slot selection.';

-- ============================================================
-- 2. Deye zero-export mode on asset_inverter
-- ============================================================

ALTER TABLE ems.asset_inverter
  ADD COLUMN IF NOT EXISTS deye_zero_export_mode SMALLINT DEFAULT 1;

COMMENT ON COLUMN ems.asset_inverter.deye_zero_export_mode IS
  'Deye reg 142 value for non-SELL modes: 1 = zero export to load (no CT), 2 = zero export to CT. Depends on physical installation.';

-- ============================================================
-- 3. Per-site seed values
-- ============================================================

-- BA81 (site_id=3, inverter_id=5): CT installed, bump degradation cost
UPDATE ems.asset_inverter SET deye_zero_export_mode = 2 WHERE id = 5;
UPDATE ems.asset_battery  SET degradation_cost_czk_kwh = 1.00 WHERE site_id = 3;

-- KV1 (site_id=4, inverter_id=7): CT installed
UPDATE ems.asset_inverter SET deye_zero_export_mode = 2 WHERE id = 7;

-- home-01 (site_id=2, inverter_id=3): no CT — default 1 is correct
