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

import { withAuth, withRateLimit } from '@/lib/api/helpers';
import { db } from '@/lib/db';
import { systemSettings } from '@/lib/db/schema/system';
import { calculateBulkScores } from '@/lib/services/interest-scoring.service';
import { CodedError, errorResponse } from '@/lib/errors';

// Bulk scoring is pure SQL + Redis (no LLM spend), so this only carries
// the 60/min/user rate-limit as a DoS backstop - no budget gate needed
// (auditor H9/H12).
export const GET = withAuth(
  withRateLimit('ai', async (_req, ctx) => {
    try {
      // Feature flag check
      const flag = await db.query.systemSettings.findFirst({
        where: and(
          eq(systemSettings.key, 'ai_interest_scoring'),
          eq(systemSettings.portId, ctx.portId),
        ),
      });
      if (flag?.value !== true) {
        throw new CodedError('NOT_FOUND', {
          internalMessage: 'AI bulk interest-score feature flag disabled for this port',
        });
      }

      const scores = await calculateBulkScores(ctx.portId);
      return NextResponse.json({ data: scores });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
