/* OPERANALYTICS-834
  договора последнего начисления для кампаний в Директе

Алгоритм из https://st.yandex-team.ru/PAYSUP-611937#5ea188932a9cd1527ceb53d5:
Есть заказ (запись в t_order, вяжется с директовской campaigns по t_order.service_id = 7 and t_order.service_order_id = campaigns.cid)
Заказ может быть связан, а может не быть связан с зачислением (t_consume) через t_order.id = t_consume.parent_order_id. Зачислений может быть несколько и это нормально. Зачисления могут быть связаны с разными счетами или с одним счетом и это тоже нормально.

Дальше вил
- Если по заказу есть зачисление, то оно связано со счетом t_invoice, в котором есть номер договора если это счет по договору и contract_id is null, если оферта
- Если по заказу зачисления нет, нужно проверить зачисление на общем счете (group_order_id в t_order -> t_order.id) и дальше использовать общую логику
*/
USE hahn;

$direct_campaigns = (
SELECT
  c.cid AS cid
, c.type AS type
, c.wallet_cid AS wallet_cid
, nvl(w.type, '') AS wallet_type
FROM `//home/direct/db/campaigns` AS c
LEFT JOIN `//home/direct/db/campaigns` AS w
  ON c.wallet_cid = w.cid
);


$bo_direct_last_consume_contract = (
SELECT *
FROM (
  SELECT MAX_BY(TableRow(), consume_dt)
  FROM (
    SELECT
      bo.service_order_id AS service_order_id
    , c.dt AS consume_dt
    , i.dt AS invoice_dt
    , ct.dt AS contract_dt
    , c.parent_order_id AS consume_parent_order_id
    , c.invoice_id AS invoice_id
    , i.external_id AS invoice_eid
    , ct.contract_id AS contract_id
    , nvl(ct.contract_eid, 'oferta-' || CAST(bo.service_order_id AS String)) AS contract_eid
    FROM `//home/balance/prod/bo/t_order` AS bo
    JOIN `//home/balance/prod/bo/t_consume` AS c
      ON bo.id = c.parent_order_id
    JOIN `//home/balance/prod/bo/t_invoice` AS i
      ON c.invoice_id = i.id
    LEFT JOIN `//home/balance/prod/bo/v_contract_apex_full` AS ct
      ON i.contract_id = ct.contract_id
    WHERE bo.service_id = 7  -- Директ
      AND bo.service_order_id > 0  -- не проверял, но такое точно не нужно
  )
  GROUP BY service_order_id
)
FLATTEN COLUMNS
);

$create_contract = ($x) -> {
  RETURN AsStruct(
      Unwrap($x.cid) AS cid
    , nvl($x.wallet_cid, 0) AS wallet_cid
    , nvl($x.invoice_source_type, '') AS invoice_source_type
    , nvl($x.contract_id, 0) AS contract_id
    , nvl($x.contract_eid, '') AS contract_eid
    , nvl($x.consume_dt, '') AS consume_dt
    , nvl($x.invoice_dt, '') AS invoice_dt
    , nvl($x.contract_dt, '') AS contract_dt
    , nvl($x.invoice_id, 0) AS invoice_id
    , nvl($x.invoice_eid, '') AS invoice_eid
    , nvl($x.consume_parent_order_id, 0) AS consume_parent_order_id
  );
};

INSERT INTO `//home/vipplanners/dict/balance/cid_last_contract` WITH TRUNCATE
SELECT *
FROM (
  SELECT
    IF(
      last_consume_wallet_contract.consume_dt >= last_consume_campaign_contract.consume_dt,
      last_consume_wallet_contract,
      last_consume_campaign_contract
    ) AS last_consume_contract
  FROM (
    SELECT
      c.cid AS cid
    , $create_contract(
        AsStruct(
          c.cid AS cid
        , c.wallet_cid AS wallet_cid
        , c.type AS invoice_source_type
        , ci.contract_id AS contract_id
        , ci.contract_eid AS contract_eid
        , ci.consume_dt AS consume_dt
        , ci.invoice_dt AS invoice_dt
        , ci.contract_dt AS contract_dt
        , ci.invoice_id AS invoice_id
        , ci.invoice_eid AS invoice_eid
        , ci.consume_parent_order_id AS consume_parent_order_id
    )) AS last_consume_campaign_contract
    , $create_contract(
        AsStruct(
          c.cid AS cid
        , c.wallet_cid AS wallet_cid
        , c.wallet_type AS invoice_source_type
        , wi.contract_id AS contract_id
        , wi.contract_eid AS contract_eid
        , wi.consume_dt AS consume_dt
        , wi.invoice_dt AS invoice_dt
        , wi.contract_dt AS contract_dt
        , wi.invoice_id AS invoice_id
        , wi.invoice_eid AS invoice_eid
        , wi.consume_parent_order_id AS consume_parent_order_id
    )) AS last_consume_wallet_contract
    FROM $direct_campaigns AS c
    LEFT JOIN $bo_direct_last_consume_contract AS ci
      ON c.cid = ci.service_order_id
    LEFT JOIN $bo_direct_last_consume_contract AS wi
      ON c.wallet_cid = wi.service_order_id
  )
)
FLATTEN COLUMNS
ORDER BY cid
;
