-- Permission 2.0: atomic tenant quota reservations for GPU-backed tasks.
-- This migration is additive and safe to run repeatedly.

CREATE TABLE IF NOT EXISTS tenant_quota_reservations (
    id TEXT PRIMARY KEY,
    tenant_id TEXT NOT NULL,
    owner_type TEXT NOT NULL,
    owner_id TEXT NOT NULL,
    gpu_count INTEGER NOT NULL DEFAULT 0,
    storage_bytes BIGINT NOT NULL DEFAULT 0,
    status TEXT NOT NULL DEFAULT 'reserved',
    create_time TEXT NOT NULL,
    released_at TEXT
);

CREATE INDEX IF NOT EXISTS idx_tenant_quota_reservations_tenant
    ON tenant_quota_reservations(tenant_id, status);
CREATE INDEX IF NOT EXISTS idx_tenant_quota_reservations_owner
    ON tenant_quota_reservations(owner_type, owner_id, status);
CREATE UNIQUE INDEX IF NOT EXISTS uq_tenant_quota_reservations_active_owner
    ON tenant_quota_reservations(owner_type, owner_id) WHERE status = 'reserved';
