import { NextResponse } from 'next/server';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { CLIENT_ARCHIVE_ACTION } from '@/lib/auth/permissions';
import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import { getClientById, updateClient, archiveClient } from '@/lib/services/clients.service';
import { updateClientSchema } from '@/lib/validators/clients';

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

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

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