export const dynamic = 'force-dynamic';

import { NextRequest, NextResponse } from 'next/server';
import prisma from '@/lib/db';
import { getActivePatterns, checkForSignificantPatterns } from '@/lib/order-to-cash/pattern-engine';

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const action = searchParams.get('action');
    const patternType = searchParams.get('type');

    if (action === 'significant') {
      const patterns = await checkForSignificantPatterns();
      return NextResponse.json({ patterns });
    }

    if (action === 'all') {
      const patterns = await prisma.detectedPattern.findMany({
        orderBy: [{ confidence: 'desc' }, { sampleSize: 'desc' }],
        take: 100,
      });
      return NextResponse.json({ patterns });
    }

    const patterns = await getActivePatterns(patternType || undefined);
    return NextResponse.json({ patterns });
  } catch (error) {
    console.error('Error fetching patterns:', error);
    return NextResponse.json({ error: 'Failed to fetch patterns' }, { status: 500 });
  }
}
