-- Migration: Create audit_logs table for centralized audit logging
-- Categories: auth, vehicle, user, system, admin
-- Severity levels: info, warning, error

CREATE TABLE IF NOT EXISTS audit_logs (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  category VARCHAR(20) NOT NULL CHECK (category IN ('auth', 'vehicle', 'user', 'system', 'admin')),
  severity VARCHAR(10) NOT NULL CHECK (severity IN ('info', 'warning', 'error')),
  user_id VARCHAR(255),
  action VARCHAR(500) NOT NULL,
  resource_type VARCHAR(100),
  resource_id VARCHAR(255),
  details JSONB,
  created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);

-- B-tree indexes for filtered queries
CREATE INDEX idx_audit_logs_category_created ON audit_logs(category, created_at DESC);
CREATE INDEX idx_audit_logs_severity_created ON audit_logs(severity, created_at DESC);
CREATE INDEX idx_audit_logs_user_created ON audit_logs(user_id, created_at DESC);
CREATE INDEX idx_audit_logs_created ON audit_logs(created_at DESC);

-- GIN index for text search on action column (requires pg_trgm extension)
CREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE INDEX idx_audit_logs_action_gin ON audit_logs USING gin (action gin_trgm_ops);

-- Comment for documentation
COMMENT ON TABLE audit_logs IS 'Centralized audit log for all system events across categories';
COMMENT ON COLUMN audit_logs.category IS 'Event category: auth, vehicle, user, system, admin';
COMMENT ON COLUMN audit_logs.severity IS 'Event severity: info, warning, error';
COMMENT ON COLUMN audit_logs.user_id IS 'User who performed the action (null for system actions)';
COMMENT ON COLUMN audit_logs.action IS 'Human-readable description of the action';
COMMENT ON COLUMN audit_logs.resource_type IS 'Type of resource affected (e.g., vehicle, backup)';
COMMENT ON COLUMN audit_logs.resource_id IS 'ID of the affected resource';
COMMENT ON COLUMN audit_logs.details IS 'Additional structured data about the event';
