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

export async function GET(
  req: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const session = await getServerSession(authOptions);

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

    const contract = await prisma.contract.findUnique({
      where: { id: params.id }
    });

    if (!contract) {
      return NextResponse.json({ error: 'Contract not found' }, { status: 404 });
    }

    // Authorization check
    if (
      session.user.role === 'CUSTOMER' && 
      contract.userId !== session.user.id
    ) {
      return NextResponse.json({ error: 'Access denied' }, { status: 403 });
    }

    if (!contract.pdfStoragePath) {
      return NextResponse.json({ error: 'Contract PDF not found' }, { status: 404 });
    }

    // Get signed URL
    const signedUrl = await downloadFile(contract.pdfStoragePath);

    return NextResponse.json({ 
      downloadUrl: signedUrl,
      filename: `contract-${contract.contractNumber}.pdf`
    });
  } catch (error) {
    console.error('Error downloading contract:', error);
    return NextResponse.json(
      { error: 'Failed to download contract' },
      { status: 500 }
    );
  }
}
