view: dt_perf_rights_territory_label {
  derived_table: {
    sql:
    WITH label_territories AS (
        SELECT id, TRY_TO_NUMBER(a.value::string) AS country_id
        FROM royalty_accounting_reporting.prod.vw_dim_abacus_ar_vendor_contract,
        LATERAL FLATTEN(INPUT => SPLIT(royalty_collection_territory, ',')) a
    )
    SELECT v.vendor_id, LISTAGG(DISTINCT c.name, '; ') WITHIN GROUP (ORDER BY c.name ASC) AS list_territories
    FROM royalty_accounting_reporting.prod.vw_dim_abacus_ar_vendor v
        INNER JOIN intelligence.dbt_prod.active_vendor_contracts vw ON v.vendor_id = vw.vendor_id
        LEFT JOIN label_territories lt ON vw.vendor_contract_id = lt.id
        LEFT JOIN orchard_app_reporting_v2.art_relations_prod_art_relations.country c ON lt.country_id = c.id
    GROUP BY 1 ;;
  }

  dimension: vendor_id {
    type: number
    sql: ${TABLE}.vendor_id ;;
    primary_key: yes
    hidden: yes
  }

  dimension: list_territories {
    type: string
    sql: ${TABLE}.list_territories ;;
    view_label: "Label"
    label: "Performance Rights Territories"
    html:
    {% assign countries = value | split: ";" %}
    {% unless {{countries.size}} == 0 %}

    <details>
    <summary>Detail ({{countries.size}})</summary>

    <ul>
    {% for country in countries %}
    <li>{{country}}</li>
    {% endfor %}
    </ul>
    </details>

    {% endunless %}
    ;;
  }
}