import { Hono } from 'hono';
import { z } from 'zod';

import { getCallStats, queryCalls } from '@/features/icalls';
import type { CallFilter } from '@/entities/call';

const listQuerySchema = z.object({
  deviceId: z.string().uuid().optional(),
  direction: z.string().optional(),
  callType: z.string().optional(),
  since: z.string().datetime().optional(),
  limit: z.coerce.number().int().positive().max(1000).default(200),
  offset: z.coerce.number().int().nonnegative().default(0),
});

export const callsMyRouter = new Hono()
  .get('/stats', async (c) => {
    const deviceId = c.req.query('deviceId');
    const stats = await getCallStats(deviceId);
    return c.json({ success: true, data: stats });
  })
  .get('/', async (c) => {
    const parsed = listQuerySchema.safeParse({
      deviceId: c.req.query('deviceId'),
      direction: c.req.query('direction'),
      callType: c.req.query('callType'),
      since: c.req.query('since'),
      limit: c.req.query('limit'),
      offset: c.req.query('offset'),
    });
    if (!parsed.success) {
      return c.json({ success: false, error: { code: 'validation_error', issues: parsed.error.flatten() } }, 400);
    }
    const filter: CallFilter = {
      deviceId: parsed.data.deviceId,
      direction: parsed.data.direction,
      callType: parsed.data.callType,
      since: parsed.data.since,
      limit: parsed.data.limit,
      offset: parsed.data.offset,
    };
    const calls = await queryCalls(filter);
    return c.json({ success: true, data: { calls } });
  });
