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

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

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

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

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

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