-- Create audit log table for COPPA/GDPR compliance
CREATE TABLE IF NOT EXISTS audit_log (
  id VARCHAR(20) PRIMARY KEY,
  user_id VARCHAR(20) REFERENCES users(id) ON DELETE SET NULL,
  action VARCHAR(50) NOT NULL,
  entity_type VARCHAR(50) NOT NULL,
  entity_id VARCHAR(20),
  changes JSONB,
  ip_address VARCHAR(45),
  user_agent TEXT,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- Create indexes for common queries
CREATE INDEX IF NOT EXISTS idx_audit_log_user_id ON audit_log(user_id);
CREATE INDEX IF NOT EXISTS idx_audit_log_entity ON audit_log(entity_type, entity_id);
CREATE INDEX IF NOT EXISTS idx_audit_log_action ON audit_log(action);
CREATE INDEX IF NOT EXISTS idx_audit_log_created_at ON audit_log(created_at);

-- Add comment
COMMENT ON TABLE audit_log IS 'Audit trail for all data access and modifications (COPPA/GDPR compliance)';
COMMENT ON COLUMN audit_log.action IS 'Action performed: CREATE, READ, UPDATE, DELETE, EXPORT, LOGIN, LOGOUT';
COMMENT ON COLUMN audit_log.entity_type IS 'Type of entity: user, child, activity, family, etc.';
COMMENT ON COLUMN audit_log.changes IS 'JSON object containing before/after values for updates';
