BEGIN;

CREATE TABLE kategorien (
    id UUID PRIMARY KEY,
    key TEXT NOT NULL UNIQUE,
    name TEXT NOT NULL,
    description TEXT,
    sort_order INTEGER NOT NULL DEFAULT 0
);

ALTER TABLE merkmale ADD COLUMN kategorie_id UUID
    REFERENCES kategorien(id)
    ON DELETE SET NULL;

ALTER TABLE merkmale ADD COLUMN im_auftragskatalog BOOLEAN NOT NULL DEFAULT FALSE;

CREATE TABLE device_merkmale (
    id UUID PRIMARY KEY,
    device_id UUID NOT NULL
        REFERENCES devices(id)
        ON DELETE CASCADE,
    merkmal_id UUID NOT NULL
        REFERENCES merkmale(id)
        ON DELETE RESTRICT,
    aktiv BOOLEAN NOT NULL,
    created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
    UNIQUE (device_id, merkmal_id)
);

CREATE TABLE device_merkmal_events (
    id UUID PRIMARY KEY,
    device_id UUID NOT NULL
        REFERENCES devices(id)
        ON DELETE CASCADE,
    merkmal_id UUID NOT NULL
        REFERENCES merkmale(id)
        ON DELETE RESTRICT,
    event_type TEXT NOT NULL
        CHECK (event_type IN (
            'selected',
            'deselected',
            'applied',
            'apply_failed',
            'removed',
            'remove_failed'
        )),
    detail JSONB,
    occurred_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);

COMMIT;
