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

import { getCallStats, ingestCalls } from '@/features/icalls';
import { withSyncHistory } from '@/shared/sync-history';

const callPayloadSchema = z.object({
  uniqueId: z.string().min(1),
  address: z.string().nullish(),
  normalizedAddress: z.string().nullish(),
  contactName: z.string().nullish(),
  direction: z.string().nullish(),
  callType: z.string().nullish(),
  answered: z.boolean().nullish(),
  durationSeconds: z.number().nullish(),
  startedAt: z.string().nullish(),
  serviceProvider: z.string().nullish(),
});

const syncCallsSchema = z.object({
  calls: z.array(callPayloadSchema),
});

export const icallsClientRouter = new Hono()
  .get('/stats', async (c) => {
    const deviceId = c.get('deviceId');
    const stats = await getCallStats(deviceId);
    return c.json({ success: true, data: stats });
  })
  .post('/sync', async (c) => {
    const deviceId = c.get('deviceId');
    const payload = syncCallsSchema.parse(await c.req.json());
    const result = await withSyncHistory(deviceId, 'calls', () => ingestCalls(deviceId, payload));
    return c.json({ success: true, data: result });
  });
