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

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

export const GET = withAuth(
  withPermission('interests', 'view', async (_req, ctx, params) => {
    try {
      const id = params.id;
      if (!id) throw new NotFoundError('interest');
      const exists = await db
        .select({ id: interests.id })
        .from(interests)
        .where(and(eq(interests.id, id), eq(interests.portId, ctx.portId)))
        .limit(1);
      if (exists.length === 0) throw new NotFoundError('interest');
      const data = await loadEntityActivity({
        portId: ctx.portId,
        entityType: 'interest',
        entityId: id,
      });
      return NextResponse.json({ data });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
