-- Date d'ancrage fix. Période 1 = 2023-12-17 => 2023-12-30
-- Definition des bornes d'archivage et de visionnement futur ( 6 mois avant la periode actuelle et 1 mois apres la periode actuelle)
-- Label pour affichage
-- Determination des dates d'une periode
CREATE OR REPLACE VIEW pay_period AS
WITH
  anchor AS (
    SELECT '2023-12-17'::date AS anchor_sunday
  ),
  series AS (
    SELECT
      gs::date                        AS period_start,    -- Dimanche
      (gs + INTERVAL '13 days')::date AS period_end,      -- Samedi
      (gs + INTERVAL '18 days')::date AS payday           -- Jeudi suivant pour viser l'année fiscale
    FROM generate_series(
      (SELECT anchor_sunday FROM anchor),
      (CURRENT_DATE + INTERVAL '1 month')::date,
      INTERVAL '14 days'
    ) AS gs
  ),
  numbered AS (
    SELECT 
      period_start,
      period_end,
      payday,
      EXTRACT(YEAR FROM payday)::int AS pay_year,
      ROW_NUMBER() OVER (
        PARTITION BY EXTRACT(YEAR FROM payday)
        ORDER BY payday
      ) AS pay_period_no
    FROM series
  )
  SELECT
    pay_year,
    pay_period_no,
    period_start,
    period_end,
    payday,
    to_char(period_start, 'YYYY-MM-DD') || '->' ||
    to_char(period_end, 'YYYY-MM-DD') AS label
  FROM numbered

  WHERE payday BETWEEN (CURRENT_DATE - INTERVAL '6 months')::date
                   AND (CURRENT_DATE + INTERVAL '1 month')::date
  ORDER BY period_start;