-- ==========================================
-- Migration 017: Audit Log
-- ==========================================
-- Immutable append-only log of all mutating actions.
-- Required for enterprise compliance (SOC2, FedRAMP, HIPAA).
-- ==========================================

-- Drop stale table if left from a prior partial run
DROP TABLE IF EXISTS audit_log CASCADE;

CREATE TABLE audit_log (
    id              UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    actor_id        UUID REFERENCES users(id) ON DELETE SET NULL,
    action          VARCHAR(100) NOT NULL,       -- e.g. 'user.create', 'team.add_member'
    resource_type   VARCHAR(50) NOT NULL,        -- e.g. 'user', 'team', 'preset', 'channel'
    resource_id     VARCHAR(255),                -- UUID or identifier of affected resource
    metadata        JSONB DEFAULT '{}'::jsonb,   -- action-specific details
    ip_address      VARCHAR(45),                 -- IPv4 or IPv6
    user_agent      TEXT DEFAULT '',
    created_at      TIMESTAMPTZ DEFAULT NOW()
);

-- Time-range queries (admin viewer, compliance exports)
CREATE INDEX idx_audit_log_created ON audit_log(created_at DESC);

-- Filter by actor
CREATE INDEX idx_audit_log_actor ON audit_log(actor_id) WHERE actor_id IS NOT NULL;

-- Filter by resource
CREATE INDEX idx_audit_log_resource ON audit_log(resource_type, resource_id);

-- Filter by action
CREATE INDEX idx_audit_log_action ON audit_log(action);

COMMENT ON TABLE audit_log IS 'Immutable audit trail of all mutating operations';
COMMENT ON COLUMN audit_log.action IS 'Dotted action name: resource.verb (e.g. user.create, team.add_member)';
COMMENT ON COLUMN audit_log.metadata IS 'Action-specific context: old/new values, affected fields, etc.';
