config {
  type: "{{ 'incremental' if incremental else 'table' }}",
  schema: "{{ dataset_id or 'warehouse' }}",
  name: "{{ table_name }}",
  {%- if partition_by %}
  bigquery: {
    partitionBy: "{{ partition_by }}",
    {%- if cluster_by %}
    clusterBy: {{ cluster_by | tojson }},
    {%- endif %}
  },
  {%- endif %}
  {%- if tags %}
  tags: {{ tags | tojson }},
  {%- endif %}
  {%- if description %}
  description: "{{ description }}",
  {%- endif %}
  {%- if dependencies %}
  dependencies: {{ dependencies | tojson }},
  {%- endif %}
}

-- Fact Table: {{ table_name }}
-- Layer: WAREHOUSE (Gold)
-- Purpose: Transactional facts for analytics
-- Generated by: dataform-warehouse-blueprints v0.1.0
-- Grain: {{ primary_keys | join(', ') if primary_keys else 'One row per transaction' }}

SELECT
  -- Fact Keys
{%- for key in primary_keys %}
  {{ key }},
{%- endfor %}
  
  -- Measures & Attributes
{%- for column in columns %}
  {%- if column not in primary_keys %}
  {{ column }}{{ "," if not loop.last else "" }}
  {%- endif %}
{%- endfor %}
  
  -- Audit Columns
  CURRENT_TIMESTAMP() AS _loaded_at,
  '{{ table_name }}' AS _source_table
  
FROM {{ source_table }}

{%- if incremental %}

${ when(incremental(), `
  WHERE {{ partition_by or 'updated_at' }} > (
    SELECT MAX({{ partition_by or 'updated_at' }}) FROM ${self()}
  )
`) }

{%- endif %}

