/*******Main Section**************************************************************************/
\set ON_ERROR_STOP on
\set AUTOCOMMIT on
\timing on
 
DELETE FROM data_api.customer_events;

insert into  data_api.customer_events ( 
	 id_str 
	, date 
	, last_updated 
	, customer_id_str 
	, create_method 
	, customer_id 
	, external_id 
	, id 
	, source 
	, event 
	, content_name 
	,etl_tx_dt
)
select 
	 case when trim(both from id_str)='' then null else  id_str::text  end  id_str 
	, case when trim(both from date)='' then null else  date::text  end  date 
	, case when trim(both from last_updated)='' then null else  last_updated::text  end  last_updated 
	, case when trim(both from customer_id_str)='' then null else  customer_id_str::text  end  customer_id_str 
	, case when trim(both from create_method)='' then null else  create_method::text  end  create_method 
	, case when trim(both from customer_id)='' then null else  customer_id::text  end  customer_id 
	, case when trim(both from external_id)='' then null else  external_id::text  end  external_id 
	, case when trim(both from id)='' then null else  id::text  end  id 
	, case when trim(both from source)='' then null else  source::text  end  source 
	, case when trim(both from event)='' then null else  event::text  end  event 
	, case when trim(both from content_name)='' then null else  content_name::text  end  content_name 
,etl_tx_dt
from (
select 
	 (json_array_elements(data::json)::json->>'idStr')  id_str 
	, (json_array_elements(data::json)::json->>'date')  date 
	, (json_array_elements(data::json)::json->>'lastUpdated')  last_updated 
	, (json_array_elements(data::json)::json->>'customerIdStr')  customer_id_str 
	, (json_array_elements(data::json)::json->>'createMethod')  create_method 
	, (json_array_elements(data::json)::json->>'customerId')  customer_id 
	, (json_array_elements(data::json)::json->>'externalId')  external_id 
	, (json_array_elements(data::json)::json->>'id')  id 
	, (json_array_elements(data::json)::json->>'source')  source 
	, (json_array_elements(data::json)::json->>'event')  event 
	, (json_array_elements(data::json)::json->>'contentName')  content_name 
	,CURRENT_TIMESTAMP(0)  etl_tx_dt
from (select * from data_api.api_data 
WHERE api_id='747d33fa-a0e0-421d-aa9b-4ca4517b' and is_loaded = '0' order by request_tm desc limit 1) p )p;

update  data_api.api_data 
set is_loaded = '1' ,
	status = '1',
	request_tm = current_timestamp(0)
where api_id='747d33fa-a0e0-421d-aa9b-4ca4517b';
\q