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('companies', 'view', async (req, ctx, params) => {
    try {
      const companyId = params.id;
      if (!companyId) throw new NotFoundError('Company');
      const aggregate = new URL(req.url).searchParams.get('aggregate') === 'true';
      const notes = aggregate
        ? await notesService.listForCompanyAggregated(ctx.portId, companyId)
        : await notesService.listForEntity(ctx.portId, 'companies', companyId);
      return NextResponse.json({ data: notes });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);

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

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

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