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

const addAddressSchema = 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 GET = withAuth(
  withPermission('clients', 'view', async (req, ctx, params) => {
    try {
      const rows = await listClientAddresses(params.id!, ctx.portId);
      return NextResponse.json({ data: rows });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);

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