-- 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_date
  ),
  bounds AS (
    SELECT
    --ajouter vérification de la période actuel, validations et revoir la logique
      (now()::date - INTERVAL '6 months')::date AS start_bound,
      (now()::date + INTERVAL '1 month')::date AS end_bound,
      anchor.anchor_date
    FROM anchor
  ),
  series AS (
    SELECT
      generate_series(bounds.start_bound, bounds.end_bound, '14 days') AS period_start,
      bounds.anchor_date
    FROM bounds
  )
SELECT
  ((row_number() OVER (ORDER BY period_start) - 1) % 26) + 1 AS period_number,
  period_start                       AS start_date,
  period_start + INTERVAL '13 days'  AS end_date,
  EXTRACT(YEAR FROM period_start)::int AS year,
  period_start || ' → ' ||
    to_char(period_start + INTERVAL '13 days', 'YYYY-MM-DD')
    AS label
FROM series
ORDER BY period_start;
