-- =============================================================
-- V080__seed_site_hulin_bess.sql
-- Idempotentní seed BESS lokality Hulín, Krátká 780 (bez FVE, nízká vlastní spotřeba).
-- Střídač Deye 2×20 kW (AC max 40 kW), baterie 4×32 kWh (128 kWh usable).
-- BMS z/do baterie max 2×350 A (~36 kW); jistič import ~63 A (~43 kW); export max 42 kW.
-- Viz docs/new-site-setup-template.md (sekce BESS bez FVE).
-- =============================================================

do $$
declare
    v_site_code text := 'hulin-bess';

    -- Modbus host doplnit před zapnutím endpointu (enabled = true).
    v_host_deye text := '0.0.0.0';
    v_port_deye int  := 502;

    v_site_id  int;
    v_ep_deye  int;
    v_inv_main int;
begin
    insert into ems.site (code, name, timezone, latitude, longitude, active, notes)
    values (
        v_site_code,
        'Hulín, Krátká 780 (BESS)',
        'Europe/Prague',
        49.312314,
        17.474594,
        true,
        'Adresa: Krátká 780, 768 24 Hulín. BESS – ukládání energie bez FVE, bez významné vlastní spotřeby. '
        'Střídač Deye 2×20 kW; baterie 4×32 kWh; BMS max ~36 kW z/do baterie; jistič ~43 kW import, export 42 kW. '
        'Souřadnice pro případnou budoucí FVE / počasí. Modbus endpoint zatím vypnutý – doplnit IP a enabled.'
    )
    on conflict (code) do update set
        name      = excluded.name,
        timezone  = excluded.timezone,
        latitude  = excluded.latitude,
        longitude = excluded.longitude,
        active    = excluded.active,
        notes     = excluded.notes
    returning id into v_site_id;

    select se.id into v_ep_deye
    from ems.site_endpoint se
    where se.site_id = v_site_id
      and se.endpoint_type = 'modbus_tcp'
      and se.notes ilike '%Deye%'
    order by se.id
    limit 1;

    if v_ep_deye is null then
        insert into ems.site_endpoint (
            site_id, endpoint_type, host, port, protocol, unit_id, enabled, notes
        )
        values (
            v_site_id, 'modbus_tcp', v_host_deye, v_port_deye, 'modbus_tcp', 1, false,
            'Deye 2×20 kW – Modbus TCP (Waveshare). Host/IP doplnit před enabled = true.'
        )
        returning id into v_ep_deye;
    end if;

    insert into ems.site_grid_connection (
        site_id,
        max_import_power_w,
        max_export_power_w,
        no_export,
        reserved_capacity_w,
        block_export_on_negative_sell,
        notes
    )
    values (
        v_site_id,
        43000,
        42000,
        false,
        0,
        true,
        'Hlavní jistič ~63 A → import cca 43 kW. Export do DS max 42 kW. '
        'BESS bez FVE – block_export_on_negative_sell pro zápornou výkupní cenu v LP.'
    )
    on conflict (site_id) do update set
        max_import_power_w            = excluded.max_import_power_w,
        max_export_power_w            = excluded.max_export_power_w,
        no_export                     = excluded.no_export,
        reserved_capacity_w           = excluded.reserved_capacity_w,
        block_export_on_negative_sell = excluded.block_export_on_negative_sell,
        notes                         = excluded.notes;

    if not exists (
        select 1 from ems.site_market_config smc
        where smc.site_id = v_site_id and smc.valid_to is null
    ) then
        insert into ems.site_market_config (
            site_id,
            purchase_pricing_mode, sale_pricing_mode,
            buy_margin_fixed_czk, buy_margin_percent,
            sell_margin_fixed_czk, sell_margin_percent,
            currency, valid_from, valid_to, notes,
            tariff_id, hdo_code_id, system_services_czk_kwh, ote_fee_czk_kwh
        )
        values (
            v_site_id,
            'spot', 'spot',
            0.050, 0,
            -0.020, 0,
            'CZK', now(), null,
            'Výchozí spot nákup/prodej (marže jako home-01). Upřesnit dle smlouvy provozovatele BESS.',
            null, null, 0, 0
        );
    end if;

    insert into ems.site_operating_mode (site_id, mode_code, activated_by, notes)
    values (
        v_site_id,
        'MANUAL',
        'migration:V080_seed_site_hulin_bess',
        'Start MANUAL (bez zápisů na Deye). Po ověření Modbus a SoC přepnout na AUTO.'
    )
    on conflict (site_id) do nothing;

    select ai.id into v_inv_main
    from ems.asset_inverter ai
    where ai.site_id = v_site_id and ai.code = 'deye-main'
    limit 1;

    if v_inv_main is null then
        insert into ems.asset_inverter (
            site_id, code, manufacturer, model, endpoint_id,
            max_charge_power_w, max_discharge_power_w, max_export_power_w,
            max_ac_output_w, max_dc_input_w, max_battery_charge_w, max_battery_discharge_w,
            gen_port_max_power_w,
            deye_register_max_charge_a, deye_register_max_discharge_a,
            deye_zero_export_mode,
            controllable, active, notes
        )
        values (
            v_site_id,
            'deye-main',
            'Deye',
            '2× SUN-20K (40 kW AC)',
            v_ep_deye,
            36000, 36000, 42000,
            40000, 0, 36000, 36000,
            null,
            350, 350,
            2,
            true, true,
            'Hybrid 2×20 kW. BMS limit z/do baterie 2×350 A (~36 kW). AC/střídač max 40 kW. '
            'Reg 108/109 cap 350 A. deye_zero_export_mode=2 (CT na odběrném místě) – ověřit po instalaci.'
        )
        returning id into v_inv_main;
    end if;

    if not exists (
        select 1 from ems.asset_battery ab
        where ab.site_id = v_site_id and ab.code = 'bat-main'
    ) then
        insert into ems.asset_battery (
            site_id, inverter_id, code,
            usable_capacity_wh, min_soc_percent, reserve_soc_percent, max_soc_percent,
            charge_efficiency, discharge_efficiency, degradation_cost_czk_kwh,
            max_charge_c_rate, max_discharge_c_rate, bms_max_charge_w, bms_max_discharge_w,
            planner_max_soc_percent,
            charge_slot_buffer, discharge_slot_buffer
        )
        values (
            v_site_id, v_inv_main, 'bat-main',
            128000,
            10, 10, 95,
            0.95, 0.95,
            0.50,
            0.5, 0.5,
            36000, 36000,
            100,
            1.3, 1.5
        );
    end if;

    -- Žádné asset_pv_array / EV / TČ – čistý BESS arbitrážní uzel.

end;
$$;
