CREATE TABLE IF NOT EXISTS resource_secrets (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    organization_id UUID NOT NULL REFERENCES organizations(id) ON DELETE CASCADE,
    resource_id UUID NOT NULL REFERENCES resources(id) ON DELETE CASCADE,
    secret_ref TEXT NOT NULL UNIQUE,
    protocol TEXT NOT NULL,
    version INTEGER NOT NULL DEFAULT 1,
    key_id TEXT NOT NULL,
    algorithm TEXT NOT NULL DEFAULT 'AES-256-GCM',
    nonce BYTEA NOT NULL,
    ciphertext BYTEA NOT NULL,
    payload_sha256 TEXT NOT NULL,
    metadata JSONB NOT NULL DEFAULT '{}'::JSONB,
    created_by_user_id UUID REFERENCES users(id) ON DELETE SET NULL,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    rotated_at TIMESTAMPTZ,
    UNIQUE (resource_id)
);

CREATE INDEX IF NOT EXISTS idx_resource_secrets_organization_id
    ON resource_secrets(organization_id);

CREATE INDEX IF NOT EXISTS idx_resource_secrets_resource_id
    ON resource_secrets(resource_id);

CREATE INDEX IF NOT EXISTS idx_resource_secrets_secret_ref
    ON resource_secrets(secret_ref);
