import { NextResponse } from 'next/server';
import { eq, and } from 'drizzle-orm';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { db } from '@/lib/db';
import { clients } from '@/lib/db/schema/clients';
import {
  loadClientActivityAggregated,
  loadEntityActivity,
} from '@/lib/services/entity-activity.service';
import { errorResponse, NotFoundError } from '@/lib/errors';

export const GET = withAuth(
  withPermission('clients', 'view', async (req, ctx, params) => {
    try {
      const id = params.id;
      if (!id) throw new NotFoundError('client');
      const exists = await db
        .select({ id: clients.id })
        .from(clients)
        .where(and(eq(clients.id, id), eq(clients.portId, ctx.portId)))
        .limit(1);
      if (exists.length === 0) throw new NotFoundError('client');
      // ?aggregate=false opts out for callers that need just the
      // client-level audit log (no interest events). Default is on
      // since the Client overview Activity tab benefits from the
      // full timeline.
      const url = new URL(req.url);
      const aggregate = url.searchParams.get('aggregate') !== 'false';
      const data = aggregate
        ? await loadClientActivityAggregated({ portId: ctx.portId, clientId: id })
        : await loadEntityActivity({
            portId: ctx.portId,
            entityType: 'client',
            entityId: id,
          });
      return NextResponse.json({ data });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
