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

import { withAuth, withPermission } from '@/lib/api/helpers';
import { db } from '@/lib/db';
import { residentialClients } 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_clients', 'view', async (_req, ctx, params) => {
    try {
      await assertResidentialModuleEnabled(ctx.portId);
      const id = params.id;
      if (!id) throw new NotFoundError('residential client');
      const exists = await db
        .select({ id: residentialClients.id })
        .from(residentialClients)
        .where(and(eq(residentialClients.id, id), eq(residentialClients.portId, ctx.portId)))
        .limit(1);
      if (exists.length === 0) throw new NotFoundError('residential client');
      const data = await loadEntityActivity({
        portId: ctx.portId,
        entityType: 'residential_client',
        entityId: id,
      });
      return NextResponse.json({ data });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
