-- Migration 061: Mehrere benannte PDF-Berichte pro Nutzerprofil; Daten von report_profiles übernehmen.

CREATE TABLE IF NOT EXISTS report_definitions (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    profile_id UUID NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
    name TEXT NOT NULL DEFAULT 'Bericht',
    payload JSONB NOT NULL DEFAULT '{}'::jsonb,
    sort_order INT NOT NULL DEFAULT 0,
    updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);

CREATE INDEX IF NOT EXISTS idx_report_definitions_profile_sort
    ON report_definitions (profile_id, sort_order);

COMMENT ON TABLE report_definitions IS 'Mehrere strukturierte PDF-Berichte pro Profil (payload = ReportProfilePayload v1)';

INSERT INTO report_definitions (profile_id, name, payload, sort_order)
SELECT rp.profile_id, 'Standard', rp.payload, 0
FROM report_profiles rp
WHERE NOT EXISTS (
    SELECT 1 FROM report_definitions rd WHERE rd.profile_id = rp.profile_id
);

DROP TABLE IF EXISTS report_profiles;
