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 { updateContact, removeContact } from '@/lib/services/clients.service';
import { optionalCountryIsoSchema, optionalPhoneE164Schema } from '@/lib/validators/i18n';

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

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

export const DELETE = withAuth(
  withPermission('clients', 'edit', async (req, ctx, params) => {
    try {
      await removeContact(params.contactId!, params.id!, ctx.portId, {
        userId: ctx.userId,
        portId: ctx.portId,
        ipAddress: ctx.ipAddress,
        userAgent: ctx.userAgent,
      });
      return new NextResponse(null, { status: 204 });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
