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

export const GET = withAuth(
  withPermission('clients', 'view', async (req, ctx, params) => {
    try {
      const clientId = params.id;
      if (!clientId) throw new NotFoundError('Client');
      // ?aggregate=true unions client-level notes with notes from
      // every interest + directly-owned yacht so the Notes tab on
      // the client overview shows the full timeline.
      const url = new URL(req.url);
      const aggregate = url.searchParams.get('aggregate') === 'true';
      const notes = aggregate
        ? await notesService.listForClientAggregated(ctx.portId, clientId)
        : await notesService.listForEntity(ctx.portId, 'clients', clientId);
      return NextResponse.json({ data: notes });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);

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

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

      emitToRoom(`client:${clientId}`, 'client:noteAdded', {
        clientId,
        noteId: note.id,
        authorName: note.authorName ?? ctx.user.name,
        preview: note.content.slice(0, 100),
      });

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