import { NextResponse } from 'next/server';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { createAuditLog } from '@/lib/audit';
import { errorResponse, NotFoundError } from '@/lib/errors';
import { updateNoteSchema } from '@/lib/validators/notes';
import * as notesService from '@/lib/services/notes.service';

export const PATCH = withAuth(
  withPermission('clients', 'edit', async (req, ctx, params) => {
    try {
      const clientId = params.id;
      const noteId = params.noteId;
      if (!clientId) throw new NotFoundError('Client');
      if (!noteId) throw new NotFoundError('Note');
      const body = await parseBody(req, updateNoteSchema);
      const note = await notesService.update(ctx.portId, 'clients', clientId, noteId, body);

      void createAuditLog({
        userId: ctx.userId,
        portId: ctx.portId,
        action: 'update',
        entityType: 'client_note',
        entityId: noteId,
        metadata: { clientId },
        ipAddress: ctx.ipAddress,
        userAgent: ctx.userAgent,
      });

      return NextResponse.json({ data: note });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);

export const DELETE = withAuth(
  withPermission('clients', 'edit', async (_req, ctx, params) => {
    try {
      const clientId = params.id;
      const noteId = params.noteId;
      if (!clientId) throw new NotFoundError('Client');
      if (!noteId) throw new NotFoundError('Note');
      await notesService.deleteNote(ctx.portId, 'clients', clientId, noteId);

      void createAuditLog({
        userId: ctx.userId,
        portId: ctx.portId,
        action: 'delete',
        entityType: 'client_note',
        entityId: noteId,
        metadata: { clientId },
        ipAddress: ctx.ipAddress,
        userAgent: ctx.userAgent,
      });

      return new NextResponse(null, { status: 204 });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
