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 { calculateInterestScore } from '@/lib/services/interest-scoring.service';
import { parseQuery } from '@/lib/api/route-helpers';
import { requestScoreSchema } from '@/lib/validators/ai';
import { CodedError, errorResponse } from '@/lib/errors';

// 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 interest-score feature flag disabled for this port',
        });
      }

      const { interestId } = parseQuery(req, requestScoreSchema);
      const score = await calculateInterestScore(interestId, ctx.portId);

      return NextResponse.json({ data: score });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
