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

const updateAddressSchema = z.object({
  label: z.string().min(1).max(80).optional(),
  streetAddress: z.string().max(500).optional().nullable(),
  city: z.string().max(120).optional().nullable(),
  subdivisionIso: optionalSubdivisionIsoSchema.optional(),
  postalCode: z.string().max(40).optional().nullable(),
  countryIso: optionalCountryIsoSchema.optional(),
  isPrimary: z.boolean().optional(),
});

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

export const DELETE = withAuth(
  withPermission('clients', 'edit', async (req, ctx, params) => {
    try {
      await removeClientAddress(params.addressId!, 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);
    }
  }),
);
