-- =============================================================
-- R__vw_site_effective_price.sql
-- EMS Platform – view efektivních cen per site
-- Repeatable migration
-- =============================================================

CREATE OR REPLACE VIEW ems.vw_site_effective_price AS
SELECT
    smc.site_id,
    mip.interval_start,
    mip.interval_end,
    mip.market_source,
    -- Raw ceny
    mip.buy_raw_price_czk_kwh,
    mip.sell_raw_price_czk_kwh,
    -- Marže
    smc.buy_margin_fixed_czk,
    smc.buy_margin_percent,
    smc.sell_margin_fixed_czk,
    smc.sell_margin_percent,
    -- Efektivní ceny
    ROUND(
        mip.buy_raw_price_czk_kwh
        + smc.buy_margin_fixed_czk
        + (mip.buy_raw_price_czk_kwh * smc.buy_margin_percent / 100.0),
        6
    ) AS effective_buy_price_czk_kwh,
    ROUND(
        mip.sell_raw_price_czk_kwh
        + smc.sell_margin_fixed_czk
        + (mip.sell_raw_price_czk_kwh * smc.sell_margin_percent / 100.0),
        6
    ) AS effective_sell_price_czk_kwh
FROM ems.market_interval_price mip
CROSS JOIN ems.site_market_config smc
WHERE smc.valid_from <= mip.interval_start
  AND (smc.valid_to IS NULL OR smc.valid_to > mip.interval_start);

COMMENT ON VIEW ems.vw_site_effective_price IS
'Efektivní nákupní a prodejní ceny elektřiny per lokalita a 15min interval.
Dopočítává marže z site_market_config na raw ceny z market_interval_price.
Nezahrnuje data bez platné market_config. Používat pro plánování a audit.';
