BEGIN;

CREATE TABLE workspaces (
    id UUID PRIMARY KEY,
    organization_id UUID
        REFERENCES organizations(id)
        ON DELETE CASCADE,
    key TEXT NOT NULL,
    name TEXT NOT NULL,
    description TEXT,
    created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
    UNIQUE (organization_id, key)
);

CREATE TABLE merkmale (
    id UUID PRIMARY KEY,
    key TEXT NOT NULL UNIQUE,
    name TEXT NOT NULL,
    description TEXT
);

CREATE TABLE workspace_merkmale (
    workspace_id UUID NOT NULL
        REFERENCES workspaces(id)
        ON DELETE CASCADE,
    merkmal_id UUID NOT NULL
        REFERENCES merkmale(id)
        ON DELETE RESTRICT,
    PRIMARY KEY (workspace_id, merkmal_id)
);

CREATE TABLE backends (
    id UUID PRIMARY KEY,
    key TEXT NOT NULL UNIQUE,
    name TEXT NOT NULL,
    installer_type TEXT NOT NULL
);

CREATE TABLE blueprints (
    id UUID PRIMARY KEY,
    merkmal_id UUID NOT NULL
        REFERENCES merkmale(id)
        ON DELETE CASCADE,
    backend_id UUID NOT NULL
        REFERENCES backends(id)
        ON DELETE CASCADE,
    ansible_role TEXT NOT NULL,
    UNIQUE (merkmal_id, backend_id)
);

CREATE TABLE bereitstellungsvorlagen (
    id UUID PRIMARY KEY,
    organization_id UUID NOT NULL
        REFERENCES organizations(id)
        ON DELETE CASCADE,
    workspace_id UUID NOT NULL
        REFERENCES workspaces(id)
        ON DELETE RESTRICT,
    backend_id UUID NOT NULL
        REFERENCES backends(id)
        ON DELETE RESTRICT,
    label TEXT NOT NULL,
    is_default BOOLEAN NOT NULL DEFAULT FALSE,
    disk_encryption BOOLEAN NOT NULL DEFAULT FALSE,
    partitioning TEXT NOT NULL DEFAULT 'default',
    secure_boot_required BOOLEAN NOT NULL DEFAULT FALSE,
    created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);

CREATE UNIQUE INDEX bereitstellungsvorlagen_one_default_per_org
    ON bereitstellungsvorlagen (organization_id)
    WHERE is_default;

CREATE TABLE assignments (
    id UUID PRIMARY KEY,
    device_id UUID NOT NULL UNIQUE
        REFERENCES devices(id)
        ON DELETE CASCADE,
    bereitstellungsvorlage_id UUID NOT NULL
        REFERENCES bereitstellungsvorlagen(id)
        ON DELETE RESTRICT,
    created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE activation_codes (
    code TEXT PRIMARY KEY,
    organization_id UUID NOT NULL
        REFERENCES organizations(id)
        ON DELETE CASCADE,
    active BOOLEAN NOT NULL DEFAULT TRUE,
    created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);

COMMIT;
