/**
 * GET /api/telephony/recent-calls?limit=20&offset=0&search=&direction=all —
 * dashboard card (admin roles): missed inbound + successful outbound calls
 * from the FreePBX CDR, one row per call, optionally paged and filtered by
 * direction/number/name. Never throws to the client:
 * { status, available, rows, total }.
 */
import { isAdminVerified } from '../../utils/mobileReleases'
import { recentCalls } from '../../utils/telephony/cdr'

export default defineEventHandler(async (event) => {
  const token = await getTokenHelper(event)
  if (!token) return { status: 401, available: false, rows: [], total: 0 }
  const admin = await isAdminVerified(event, token)
  if (!admin) return { status: 403, available: false, rows: [], total: 0 }
  const query = getQuery(event)
  const limit = Math.min(50, Math.max(1, Number(query.limit) || 20))
  const offset = Math.max(0, Number(query.offset) || 0)
  const search = typeof query.search === 'string' ? query.search : ''
  const direction: 'all' | 'in' | 'out' = query.direction === 'in' ? 'in' : query.direction === 'out' ? 'out' : 'all'
  try {
    const res = await recentCalls(limit, offset, search, direction)
    return { status: 200, ...res }
  } catch (err: any) {
    console.warn('[cdr] recent calls failed:', err?.message || err)
    return { status: 502, available: false, rows: [], total: 0, message: err?.message || 'CDR unavailable' }
  }
})
