
import { NextRequest, NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';
import { prisma } from '@/lib/db';

export async function GET(req: NextRequest) {
  try {
    const session = await getServerSession(authOptions);

    if (!session) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    // For customers, only show their contracts
    const where = session.user.role === 'CUSTOMER' 
      ? { userId: session.user.id }
      : {};

    const contracts = await prisma.contract.findMany({
      where,
      include: {
        user: {
          select: {
            name: true,
            email: true,
            companyName: true,
          },
        },
        quote: {
          select: {
            quoteNumber: true,
            total: true,
            services: true,
          },
        },
        partner: {
          select: {
            companyName: true,
          },
        },
        signatures: true,
      },
      orderBy: {
        createdAt: 'desc',
      },
    });

    return NextResponse.json({ contracts });
  } catch (error) {
    console.error('Error fetching contracts:', error);
    return NextResponse.json(
      { error: 'Failed to fetch contracts' },
      { status: 500 }
    );
  }
}
