-- Migration: protection_state_log
-- Adds append-only protection-state transition log (DiGA-Kernmetrik).
--
-- Purpose:
--   Replaces the broken streaks.current_days=0 metric with a factual,
--   optimistic coverage model based on actual VPN/MDM protection state.
--   Drives GET /api/protection/coverage → protectedDays, currentStreakDays,
--   longestStreakDays, etc.
--
-- Design decisions:
--   - Append-only: never UPDATE rows, only INSERT new transitions.
--   - Dedup enforced at application layer (server + client both deduplicate).
--   - source column is VARCHAR (not enum) for forward-compatibility.
--   - Index on (user_id, occurred_at) covers the primary query pattern:
--     all events for a user ordered by time.
--
-- Non-breaking: purely additive, no existing columns modified.
--
-- Deploy: pnpm prisma migrate deploy (on server via GitHub Actions pipeline)

CREATE TABLE "rebreak"."protection_state_log" (
  "id"          UUID        NOT NULL DEFAULT gen_random_uuid(),
  "user_id"     UUID        NOT NULL,
  "active"      BOOLEAN     NOT NULL,
  "source"      VARCHAR(64) NOT NULL,
  "occurred_at" TIMESTAMPTZ NOT NULL,
  "created_at"  TIMESTAMPTZ NOT NULL DEFAULT now(),

  CONSTRAINT "protection_state_log_pkey" PRIMARY KEY ("id")
);

CREATE INDEX "protection_state_log_user_id_occurred_at_idx"
  ON "rebreak"."protection_state_log" ("user_id", "occurred_at");
