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('interests', 'edit', async (req, ctx, params) => {
    try {
      const interestId = params.id;
      const noteId = params.noteId;
      if (!interestId) throw new NotFoundError('Interest');
      if (!noteId) throw new NotFoundError('Note');
      const body = await parseBody(req, updateNoteSchema);
      const note = await notesService.update(ctx.portId, 'interests', interestId, noteId, body);

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

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

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

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

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