WITH MinUrutSeqAddr AS (
    SELECT TRIM(pda.KD_DEBITUR_SEQ) AS KD_DEBITUR_SEQ
		   , MIN(TRIM(pda.URUT_SEQ)) AS Min_URUT_SEQ_ADDR
		   , MIN(TRIM(pda.ADDR_VALUE)) AS Min_addr_value
		   , MIN(TRIM(pda.ADDR_DISPLAY)) AS Min_addr_display
		   , MIN(TRIM(`pda`.KD_CABANG)) AS Min_add_kd_cabang
		   , MIN(TRIM(`pda`.NAMA_DAERAH)) AS Min_nama_daerah
    FROM prm_debitur_addr pda
    GROUP BY pda.KD_DEBITUR_SEQ
),
MinUrutSeqComm AS (
    SELECT TRIM(pdc.KD_DEBITUR_SEQ) AS KD_DEBITUR_SEQ
           , MIN(TRIM(pdc.URUT_SEQ)) AS Min_URUT_SEQ_COMM
           , MIN(TRIM(pdc.COMM_VALUE)) AS Min_comm_value
		   , MIN(TRIM(pdc.COMM_DISPLAY)) AS Min_comm_display
		   , MIN(TRIM(`pdc`.KD_CABANG)) AS Min_comm_kd_cabang
    FROM `prm_debitur_comm` pdc
    GROUP BY pdc.KD_DEBITUR_SEQ
)
SELECT  musa.Min_addr_display AS mig_addr_display
		, musc.Min_comm_display AS mig_comm_display
		, TRIM(debitures.FLAG_OTO) AS mig_flag_oto
		, TRIM(`debitures`.KD_CABANG) AS `mig_kd_cabang`
		, musa.Min_add_kd_cabang AS `mig_kd_cabang_addr`
		, musc.Min_comm_kd_cabang AS `mig_kd_cabang_comm`
		, TRIM(`debitures`.KD_DEBITUR_SEQ) AS mig_kd_debitur_seq
		, musa.Min_nama_daerah AS mig_nama_daerah
		, TRIM(`debitures`.NO_CIF) AS `mig_no_cif`
		, CASE
			WHEN (TRIM(debitures.`NO_ID`) REGEXP '^[0-9]+$' AND LENGTH(debitures.`NO_ID`)>=16 )OR debitures.`NO_ID` IS NULL   -- 149337232533
			THEN TRIM(debitures.`NO_ID`)
			ELSE NULL
		  END AS nomor_id
		, CASE
			WHEN (TRIM(debitures.NO_ID) REGEXP '^[0-9]+$' AND LENGTH(debitures.NO_ID) >= 16) OR debitures.NO_ID IS NULL
			THEN NULL
			ELSE TRIM(debitures.NO_ID)
		  END AS mig_nomor_id2   -- TRIM(debitures.`NO_ID`) as mig_no_id
		, CASE
			WHEN musc.Min_comm_value REGEXP '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$'
			THEN musc.Min_comm_value
			ELSE NULL
		  END AS `email`
        , CASE
			WHEN musc.Min_comm_value REGEXP '^[0-9]+$'
			THEN musc.Min_comm_value
			ELSE NULL
          END AS `phone`
        , CASE
			WHEN musc.Min_comm_value REGEXP '^[0-9]+$'
			THEN NULL
			ELSE musc.Min_comm_value
          END AS `mig_phone`
		, TRIM(`debitures`.TGL_OTO) AS `mig_tgl_oto`
		, musa.Min_URUT_SEQ_ADDR AS mig_urut_seq_addr
		, musc.Min_URUT_SEQ_COMM AS mig_urut_seq_comm
		, TRIM(`debitures`.USER_OTO) AS `mig_user_oto`
		, TRIM(`debitures`.USER_UPDATE) AS `mig_user_update`
		, CASE
			WHEN `musa`.Min_addr_value IS NOT NULL
			THEN `musa`.Min_addr_value
			ELSE NULL
          END AS `address`
		, TRIM(`debitures`.KODE_CIF) AS `cif`

		, 1 AS `status`
		, TRIM(`debitures`.TGL_UPDATE) AS `created_at`
		, TRIM(`debitures`.`NAMA_DEBITUR`) AS `name`
		, TRIM(`debitures`.TGL_UPDATE) AS `updated_at`
		, 1 AS `is_mig`
FROM `prm_debitur` debitures
LEFT JOIN MinUrutSeqAddr musa ON musa.KD_DEBITUR_SEQ=debitures.KD_DEBITUR_SEQ
LEFT JOIN MinUrutSeqComm musc ON musc.KD_DEBITUR_SEQ=debitures.KD_DEBITUR_SEQ
-- WHERE musc.Min_comm_value != NULL
ORDER BY debitures.KD_DEBITUR_SEQ
