-- DiGA-Codes (Rezept-Einlösung für Krankenkassen-Pfad) + Profile-Audit-Feld.
--
-- Codes werden im Onboarding eingelöst → Plan hochstufung (Default 'legend')
-- + Trial-Modell übersprungen. Reverse-Lookup über used_by_profile_id.
--
-- Test-Codes werden in DIESER Migration mit-geseeded (REBREAK-TEST-001..010).
-- Wiederverwendung nur per manuellem SQL-Reset.

-- ─── Profile-Audit-Feld ──────────────────────────────────────────────────────

ALTER TABLE "rebreak"."profiles"
    ADD COLUMN IF NOT EXISTS "diga_code_redeemed_at" TIMESTAMPTZ NULL;

-- ─── DiGA-Codes-Tabelle ─────────────────────────────────────────────────────

CREATE TABLE IF NOT EXISTS "rebreak"."diga_codes" (
    "id"                    UUID         NOT NULL DEFAULT gen_random_uuid(),
    "code"                  TEXT         NOT NULL,
    "label"                 TEXT,
    "expires_at"            TIMESTAMPTZ,
    "used_at"               TIMESTAMPTZ,
    "used_by_profile_id"    UUID,
    "grants_plan"           TEXT         NOT NULL DEFAULT 'legend',
    "notes"                 TEXT,
    "created_at"            TIMESTAMPTZ  NOT NULL DEFAULT NOW(),
    CONSTRAINT "diga_codes_pkey"           PRIMARY KEY ("id"),
    CONSTRAINT "diga_codes_code_unique"    UNIQUE ("code"),
    CONSTRAINT "diga_codes_used_by_fk"     FOREIGN KEY ("used_by_profile_id")
        REFERENCES "rebreak"."profiles"("id") ON DELETE SET NULL
);

CREATE INDEX IF NOT EXISTS "diga_codes_used_by_idx"
    ON "rebreak"."diga_codes"("used_by_profile_id");

-- ─── Seed: 10 Test-Codes ────────────────────────────────────────────────────

INSERT INTO "rebreak"."diga_codes" ("code", "label", "grants_plan", "notes") VALUES
    ('REBREAK-TEST-001', 'test_batch_2026-05', 'legend', 'Internal test code (single-use, reset via SQL)'),
    ('REBREAK-TEST-002', 'test_batch_2026-05', 'legend', 'Internal test code (single-use, reset via SQL)'),
    ('REBREAK-TEST-003', 'test_batch_2026-05', 'legend', 'Internal test code (single-use, reset via SQL)'),
    ('REBREAK-TEST-004', 'test_batch_2026-05', 'legend', 'Internal test code (single-use, reset via SQL)'),
    ('REBREAK-TEST-005', 'test_batch_2026-05', 'legend', 'Internal test code (single-use, reset via SQL)'),
    ('REBREAK-TEST-006', 'test_batch_2026-05', 'legend', 'Internal test code (single-use, reset via SQL)'),
    ('REBREAK-TEST-007', 'test_batch_2026-05', 'legend', 'Internal test code (single-use, reset via SQL)'),
    ('REBREAK-TEST-008', 'test_batch_2026-05', 'legend', 'Internal test code (single-use, reset via SQL)'),
    ('REBREAK-TEST-009', 'test_batch_2026-05', 'legend', 'Internal test code (single-use, reset via SQL)'),
    ('REBREAK-TEST-010', 'test_batch_2026-05', 'legend', 'Internal test code (single-use, reset via SQL)')
ON CONFLICT ("code") DO NOTHING;
