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

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

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