{{
  config(
    materialized='table'
  )
}}

with distinct_cycles as (
    select 
        min(step_submission_date) as cycle_start_date,
        max(step_submission_date) as cycle_end_date,
        task_name,
        case 
            when count(case when task_status != 'Completed' then 1 end) = 0 
            then 'Closed' 
            else 'Open' 
        end as task_status
    from {{ source('tap_spreadsheets_anywhere', 'performance_review_steps') }}
    --where is_not_removed_from_task = 1
    group by task_name
),

base_records as (
    select
        dense_rank() over (order by task_name)::bigint as id,
        cycle_start_date::date               as start_date,
        cycle_end_date::date                 as end_date,
        task_name                            as name,
        'Closed'                             as status, -- overwritten logic for Sarens
        'annual'                             as type
    from distinct_cycles
),

-- Generate additional records for Performance Review 2024
additional_records as (
    select
        (select max(id) from base_records) + 1 as id,
        start_date,
        end_date,
        'Performance Review 2024 - Generic'  as name,
        status,
        type
    from base_records
    where name = 'Performance Review 2024'
    
    union all

    select
        (select max(id) from base_records) + 2 as id,
        start_date,
        end_date,
        'Performance Review 2024 - n-1 managers'  as name,
        status,
        type
    from base_records
    where name = 'Performance Review 2024'
)

-- Combine original records with additional records
select * from base_records
where name != 'Performance Review 2024'
union all
select * from additional_records