-- Phase 12: per-week weekday selection drives Arbeitstage.
--
-- Admins pick which of Mo/Di/Mi/Do/Fr are workdays for each week. The count
-- of selected days (0..5) replaces the previously free-form
-- max_working_days number input on the sprint view.
--
-- Bit layout of active_days_mask:
--   bit 0 = Mo, bit 1 = Di, bit 2 = Mi, bit 3 = Do, bit 4 = Fr
-- Default 31 = 0b11111 → Mo–Fr all active.
--
-- Backfill rule: clamp existing max_working_days to the nearest integer in
-- 0..5 (rounding .5 up) and light up that many leading bits. Half-days go
-- away at the week level; per-worker day cells still carry 0.5 granularity.

ALTER TABLE sprint_weeks
    ADD COLUMN active_days_mask INTEGER NOT NULL DEFAULT 31;

-- Backfill existing rows. CAST(x+0.5 AS INTEGER) is SQLite's "round half up"
-- for non-negative x; clamp into 0..5 and derive a mask with the first N
-- bits set: (1 << N) - 1.
UPDATE sprint_weeks
SET active_days_mask = CASE
        WHEN CAST(max_working_days + 0.5 AS INTEGER) <= 0 THEN 0
        WHEN CAST(max_working_days + 0.5 AS INTEGER) >= 5 THEN 31
        ELSE (1 << CAST(max_working_days + 0.5 AS INTEGER)) - 1
    END,
    max_working_days = CASE
        WHEN CAST(max_working_days + 0.5 AS INTEGER) <= 0 THEN 0
        WHEN CAST(max_working_days + 0.5 AS INTEGER) >= 5 THEN 5
        ELSE CAST(max_working_days + 0.5 AS INTEGER)
    END;
