
set serveroutput on
set long 999999
set linesize 200
set pagesize 5000

/* --------------------------------

CREATE COLLECTION TABLE

-------------------------------- */ 
DROP TABLE IF EXISTS parsed_markdown_files;

CREATE JSON COLLECTION TABLE IF NOT EXISTS parsed_markdown_files;



/* --------------------------------

CONVERT MD TO JSON 

-------------------------------- */ 
exec CONVERT_MDFILES_TO_JSON


/* --------------------------------

CONSULTAS

-------------------------------- */ 
-- json collection
SELECT json_serialize(data returning clob pretty) AS json_data 
FROM parsed_markdown_files;


-- merchants
SELECT docs.category, 
       docs.name
FROM parsed_markdown_files,
     JSON_TABLE(data, '$.comercios[*]'
                COLUMNS (
                  name              VARCHAR2(4000) PATH '$.name',
                  category          VARCHAR2(4000) PATH '$.category'                  
                )) docs
ORDER BY category, name;


-- beneficios por nivel
SELECT docs.nivel, 
       docs.percentual_reintegro,        
       docs.reintegro_maximo_gs
FROM parsed_markdown_files,
     JSON_TABLE(data, '$.beneficios_por_nivel[*]'
                COLUMNS (
                  nivel                   VARCHAR2(100) PATH '$.nivel',
                  percentual_reintegro    NUMBER       PATH '$.percentual_reintegro',                  
                  reintegro_maximo_gs     NUMBER       PATH '$.reintegro_maximo_gs'
                )) docs
ORDER BY 1;


-- Comércios por categoria
SELECT category, COUNT(*) AS qtd
  FROM parsed_markdown_files t,
       JSON_TABLE(t.data, '$.comercios[*]'
         COLUMNS (
           category          VARCHAR2(200) PATH '$.category'           
         ))
 GROUP BY category
 ORDER BY qtd DESC;


-- JSON Dot-Notation
SELECT 
    docs.data.promocao.titulo.string() as  titulo,
    docs.data.promocao.vigencia.data_inicio || ' a ' || docs.data.promocao.vigencia.data_fim as vigencia,
    docs.data.medios_pago.rede as rede,
    docs.data.medios_pago.qr_permitido as qr_permitido    
FROM parsed_markdown_files docs;



/* --------------------------------

DUALITY VIEW

-------------------------------- */ 
-- convert
DECLARE
  schema_sql clob;
BEGIN
  schema_sql := dbms_json_duality.infer_and_generate_schema(
                json('{"tableNames"     : [ "PARSED_MARKDOWN_FILES" ],
                       "viewNames"      : [ "T" ],                       
                       "useFlexFields"  : false,
                       "updatability"   : true,
                       "sourceSchema"   : "APP_USER"}')
                );

  execute immediate schema_sql;

  dbms_json_duality.import(table_name => 'PARSED_MARKDOWN_FILES', view_name => 'T');

  execute immediate 'rename T TO V_PARSED_MARKDOWN_FILES';
END;
/


SELECT * FROM T_ROOT;
SELECT * FROM T_BENEFICIOS_POR_NIVEL;
SELECT * FROM T_COMERCIOS;
