import { NextResponse } from 'next/server';

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

export const PATCH = withAuth(
  withPermission('residential_clients', 'edit', async (req, ctx, params) => {
    try {
      await assertResidentialModuleEnabled(ctx.portId);
      const id = params.id;
      const noteId = params.noteId;
      if (!id || !noteId) throw new NotFoundError('Residential client note');
      const body = await parseBody(req, updateNoteSchema);
      const note = await notesService.update(ctx.portId, 'residential_clients', id, noteId, body);
      return NextResponse.json({ data: note });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);

export const DELETE = withAuth(
  withPermission('residential_clients', 'edit', async (_req, ctx, params) => {
    try {
      await assertResidentialModuleEnabled(ctx.portId);
      const id = params.id;
      const noteId = params.noteId;
      if (!id || !noteId) throw new NotFoundError('Residential client note');
      await notesService.deleteNote(ctx.portId, 'residential_clients', id, noteId);
      return new NextResponse(null, { status: 204 });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
