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

import { queryContacts, queryContactsByName } from '@/features/imessage';
import type { Contact } from '@/entities/contact';

const deviceIdParam = z.string().uuid();

const byNameQuerySchema = z.object({
  name: z.string().min(1).max(100),
  deviceId: z.string().uuid().optional(),
  limit: z.coerce.number().int().positive().max(50).default(10),
});

function primaryHandle(contact: Contact): string {
  return contact.phoneNumbers[0] ?? contact.emails[0] ?? contact.handle;
}

export const contactsMyRouter = new Hono()
  .get('/', async (c) => {
    const rawDeviceId = c.req.query('deviceId');
    if (rawDeviceId !== undefined) {
      const parsed = deviceIdParam.safeParse(rawDeviceId);
      if (!parsed.success) {
        return c.json({ error: 'deviceId must be a UUID when provided' }, 400);
      }
      const contacts = await queryContacts(parsed.data);
      return c.json(contacts);
    }
    // No deviceId — return all contacts across all devices
    const contacts = await queryContacts();
    return c.json(contacts);
  })
  .get('/by-name', async (c) => {
    const parsed = byNameQuerySchema.safeParse({
      name: c.req.query('name'),
      deviceId: c.req.query('deviceId'),
      limit: c.req.query('limit'),
    });
    if (!parsed.success) {
      return c.json({ error: 'Invalid query parameters', details: parsed.error.flatten() }, 400);
    }

    const { name, deviceId, limit } = parsed.data;
    const contacts = await queryContactsByName({ name, deviceId, limit });

    return c.json({
      name,
      count: contacts.length,
      contacts: contacts.map((contact) => ({
        id: contact.id,
        displayName: contact.displayName,
        handle: contact.handle,
        primaryHandle: primaryHandle(contact),
        phoneNumbers: contact.phoneNumbers,
        emails: contact.emails,
        summaryData: contact.summaryData,
      })),
    });
  });
