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

export async function GET(req: NextRequest) {
  try {
    const session = await getServerSession(authOptions);
    
    if (!session?.user?.email) {
      return NextResponse.json(
        { error: 'Unauthorized' },
        { status: 401 }
      );
    }

    const { searchParams } = new URL(req.url);
    const page = parseInt(searchParams.get('page') || '1');
    const limit = parseInt(searchParams.get('limit') || '10');
    const offset = (page - 1) * limit;

    if (!prisma) {
      return NextResponse.json(
        { error: 'Database connection not available' },
        { status: 503 }
      );
    }

    try {
      // Get projects where user's bid was selected
      const awardedProjects = await prisma.project.findMany({
        where: {
          selectedBid: {
            freelancerId: session.user.email
          },
          status: {
            in: ['IN_PROGRESS', 'COMPLETED']
          }
        },
        include: {
          category: {
            select: {
              name: true,
              slug: true
            }
          },
          client: {
            select: {
              profile: {
                select: {
                  firstName: true,
                  lastName: true
                }
              }
            }
          },
          selectedBid: {
            select: {
              id: true,
              amount: true,
              duration: true,
              status: true,
              createdAt: true
            }
          }
        },
        orderBy: {
          updatedAt: 'desc'
        },
        skip: offset,
        take: limit
      });

      // Get total count
      const totalCount = await prisma.project.count({
        where: {
          selectedBid: {
            freelancerId: session.user.email
          },
          status: {
            in: ['IN_PROGRESS', 'COMPLETED']
          }
        }
      });

      const formattedProjects = awardedProjects.map(project => ({
        id: project.id,
        title: project.title,
        description: project.description,
        status: project.status,
        budget: project.budget,
        duration: project.duration,
        categoryName: project.category.name,
        categorySlug: project.category.slug,
        clientName: `${project.client.profile?.firstName || ''} ${project.client.profile?.lastName || ''}`.trim() || 'Anonymous',
        awardedBid: {
          id: project.selectedBid?.id,
          amount: project.selectedBid?.amount,
          duration: project.selectedBid?.duration,
          status: project.selectedBid?.status,
          awardedAt: project.selectedBid?.createdAt?.toISOString()
        },
        awardedAt: project.updatedAt.toISOString(),
        timeAgo: getTimeAgo(project.updatedAt)
      }));

      return NextResponse.json({
        success: true,
        data: {
          projects: formattedProjects,
          pagination: {
            page,
            limit,
            totalCount,
            totalPages: Math.ceil(totalCount / limit),
            hasNext: offset + limit < totalCount,
            hasPrev: page > 1
          }
        }
      });

    } catch (dbError: any) {
      console.error('Database error:', dbError);
      
      return NextResponse.json(
        { 
          error: 'Database operation failed',
          message: 'Unable to fetch awarded projects due to a database error. Please try again later.',
          details: process.env.NODE_ENV === 'development' ? dbError.message : undefined
        },
        { status: 500 }
      );
    }

  } catch (error) {
    console.error('Error fetching awarded projects:', error);
    return NextResponse.json(
      { 
        error: error instanceof Error ? error.message : 'Failed to fetch awarded projects',
        type: 'server_error'
      },
      { status: 500 }
    );
  }
}

function getTimeAgo(date: Date): string {
  const now = new Date();
  const diffInMs = now.getTime() - date.getTime();
  const diffInMinutes = Math.floor(diffInMs / (1000 * 60));
  const diffInHours = Math.floor(diffInMinutes / 60);
  const diffInDays = Math.floor(diffInHours / 24);

  if (diffInMinutes < 1) return 'Just now';
  if (diffInMinutes < 60) return `${diffInMinutes} minute${diffInMinutes > 1 ? 's' : ''} ago`;
  if (diffInHours < 24) return `${diffInHours} hour${diffInHours > 1 ? 's' : ''} ago`;
  if (diffInDays < 7) return `${diffInDays} day${diffInDays > 1 ? 's' : ''} ago`;
  return date.toLocaleDateString();
}