<?xml version="1.0" encoding="UTF-8"?>
<changelog xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:noNamespaceSchemaLocation="file:/var/app/InputFileSchema.xsd">
    <changeset
     id="DS-5888_first_batch_prod:1"
     author="efedorov"
     run-always="true"
     topic="stream.assetFinal.acousticBrainz.backfill">
        <precondition>
            <sqlquery>
                <![CDATA[
                   with first_batch as (
                   select distinct
                       dt.track_unique_id
                   from facts.prod.dim_release dr
                       left join facts.prod.dim_track dt on dt.upc = dr.releaseid
                       left join facts.prod.dim_genre dg on dg.genreid = dr.genreid
                       left join facts.prod.dim_artist da on da.artistid = dr.artistid
                   where dr.physical_product_type = 'Digital'
                       and dr.deletions = 'N'
                       and dr.release_status = 'in_content'
                       and dr.not_for_distribution = 'N'
                       and dr.sale_start_date is not null
                       and dr.sale_start_date < '2023-06-14'
                       and dt.track_unique_id <> 0
                       and not contains(dt.isrc,'ISRC')
                       and dg.genrename not in ('Educational','Video','Spoken Word')
                       and da.artistname not in ('Various Artists', 'Varios Artistas','Various')
                   qualify row_number() over(partition by dg.genrename order by random()) <= 25000
                   ),
                   asset_upload as (
                     select *
                     from ORCHARD_APP_REPORTING_V2.PROD_OWS_ASSETS_OWS_ASSETS.ASSET_UPLOAD
                     qualify row_number() over(partition by track_unique_id order by CREATED_TIMESTAMP desc) = 1
                   )
                   select 
                       CONCAT('ASSET_FINAL_ID:', af.ID) AS KEY,
                       OBJECT_CONSTRUCT(
                           'ASSET_FINAL_ID', af.ID,
                           'ASSET_UPLOAD_ID', af.ASSET_UPLOAD_ID,
                           'ASSET_TYPE', af.ASSET_TYPE,
                           'BUCKET', af.BUCKET,
                           'FILENAME', af.FILENAME
                       ) AS VALUE
                   from first_batch b
                   JOIN asset_upload AS au ON b.track_unique_id = au.track_unique_id
                   JOIN ORCHARD_APP_REPORTING_V2.PROD_OWS_ASSETS_OWS_ASSETS.ASSET_FINAL AS af ON af.ASSET_UPLOAD_ID = au.ID
                   where
                       af.ASSET_TYPE IN ('WAV')
                ]]>
            </sqlquery>
        </precondition>
    </changeset>
</changelog>
