import { NextResponse } from 'next/server';
import { z } from 'zod';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import { listContacts, addContact } from '@/lib/services/clients.service';
import { optionalCountryIsoSchema, optionalPhoneE164Schema } from '@/lib/validators/i18n';

const addContactSchema = z.object({
  channel: z.enum(['email', 'phone', 'whatsapp', 'other']),
  value: z.string().min(1),
  valueE164: optionalPhoneE164Schema.optional(),
  valueCountry: optionalCountryIsoSchema.optional(),
  label: z.string().optional(),
  isPrimary: z.boolean().optional().default(false),
  notes: z.string().optional(),
});

export const GET = withAuth(
  withPermission('clients', 'view', async (req, ctx, params) => {
    try {
      const contacts = await listContacts(params.id!, ctx.portId);
      return NextResponse.json({ data: contacts });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);

export const POST = withAuth(
  withPermission('clients', 'edit', async (req, ctx, params) => {
    try {
      const body = await parseBody(req, addContactSchema);
      const contact = await addContact(params.id!, ctx.portId, body, {
        userId: ctx.userId,
        portId: ctx.portId,
        ipAddress: ctx.ipAddress,
        userAgent: ctx.userAgent,
      });
      return NextResponse.json({ data: contact }, { status: 201 });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
