CREATE TABLE storage_volumes (
    volume_id       UUID PRIMARY KEY,
    volume_name     TEXT NOT NULL,
    uri_prefix      TEXT NOT NULL,
    is_writable     BOOLEAN NOT NULL DEFAULT true,
    available_bytes BIGINT NOT NULL DEFAULT 0
);

CREATE TABLE library_paths (
    path_id              UUID PRIMARY KEY,
    volume_id            UUID NOT NULL REFERENCES storage_volumes(volume_id),
    relative_path        TEXT NOT NULL,
    is_ingest_destination BOOLEAN NOT NULL DEFAULT false,
    ownership_policy     TEXT NOT NULL DEFAULT 'unassigned',
    designated_owner_id  UUID
);

CREATE TABLE quota_definitions (
    quota_id     UUID PRIMARY KEY,
    owner_scope  UUID NOT NULL,
    is_enforced  BOOLEAN NOT NULL DEFAULT true
);

CREATE TABLE quota_rules (
    rule_id      UUID PRIMARY KEY,
    quota_id     UUID NOT NULL REFERENCES quota_definitions(quota_id) ON DELETE CASCADE,
    dimension    TEXT NOT NULL,
    limit_value  BIGINT NOT NULL,
    time_period  TEXT NOT NULL,
    is_unlimited BOOLEAN NOT NULL DEFAULT false
);

CREATE TABLE usage_ledger (
    entry_id        UUID PRIMARY KEY,
    user_id         UUID NOT NULL REFERENCES users(id),
    usage_type      TEXT NOT NULL,
    consumed_amount BIGINT NOT NULL,
    timestamp       TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    context         TEXT NOT NULL DEFAULT ''
);

CREATE TABLE ingest_sessions (
    session_id           UUID PRIMARY KEY,
    uploader_user_id     UUID NOT NULL REFERENCES users(id),
    client_device_id     TEXT NOT NULL,
    original_filename    TEXT NOT NULL,
    client_checksum      TEXT NOT NULL,
    target_library_path_id UUID NOT NULL REFERENCES library_paths(path_id),
    status               TEXT NOT NULL DEFAULT 'uploading',
    created_at           TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    error_message        TEXT
);
