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 { createNoteSchema } from '@/lib/validators/notes';
import * as notesService from '@/lib/services/notes.service';

export const GET = withAuth(
  withPermission('yachts', 'view', async (req, ctx, params) => {
    try {
      const yachtId = params.id;
      if (!yachtId) throw new NotFoundError('Yacht');
      const aggregate = new URL(req.url).searchParams.get('aggregate') === 'true';
      const notes = aggregate
        ? await notesService.listForYachtAggregated(ctx.portId, yachtId)
        : await notesService.listForEntity(ctx.portId, 'yachts', yachtId);
      return NextResponse.json({ data: notes });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);

export const POST = withAuth(
  withPermission('yachts', 'edit', async (req, ctx, params) => {
    try {
      const yachtId = params.id;
      if (!yachtId) throw new NotFoundError('Yacht');
      const body = await parseBody(req, createNoteSchema);
      const note = await notesService.create(ctx.portId, 'yachts', yachtId, ctx.userId, body);

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

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