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,
  { params }: { params: Promise<{ projectId: string }> }
) {
  try {
    if (!prisma) {
      return NextResponse.json(
        { error: 'Database connection not available' },
        { status: 503 }
      );
    }

    const session = await getServerSession(authOptions);
    
    if (!session?.user?.email) {
      return NextResponse.json(
        { error: 'Unauthorized' },
        { status: 401 }
      );
    }

    const { projectId } = await params;

    if (!projectId) {
      return NextResponse.json(
        { error: 'Project ID is required' },
        { status: 400 }
      );
    }

    try {
      // Verify user has access to this project
      const project = await prisma.project.findFirst({
        where: {
          id: projectId,
          OR: [
            // User is the client
            { clientId: session.user.email },
            // User is the freelancer with accepted bid
            {
              bids: {
                some: {
                  freelancerId: session.user.email,
                  status: 'ACCEPTED'
                }
              }
            }
          ]
        },
        include: {
          bids: {
            where: {
              status: 'ACCEPTED'
            },
            include: {
              freelancer: {
                select: {
                  id: true,
                  email: true,
                  profile: {
                    select: {
                      firstName: true,
                      lastName: true
                    }
                  }
                }
              }
            }
          },
          client: {
            select: {
              id: true,
              email: true,
              profile: {
                select: {
                  firstName: true,
                  lastName: true
                }
              }
            }
          }
        }
      });

      if (!project) {
        return NextResponse.json(
          { error: 'Project not found or access denied' },
          { status: 404 }
        );
      }

      const timelineEvents = [];

      // Project creation event
      timelineEvents.push({
        id: `created-${project.id}`,
        type: 'created',
        title: 'Project Created',
        description: 'Project was posted and is now accepting bids',
        timestamp: project.createdAt.toISOString(),
        actor: `${project.client.profile?.firstName || ''} ${project.client.profile?.lastName || ''}`.trim() || 'Unknown Client',
        actorRole: 'client'
      });

      // Get bids events
      const bids = await prisma.bid.findMany({
        where: { projectId: projectId },
        include: {
          freelancer: {
            select: {
              id: true,
              email: true,
              profile: {
                select: {
                  firstName: true,
                  lastName: true
                }
              }
            }
          }
        },
        orderBy: { createdAt: 'asc' }
      });

      bids.forEach(bid => {
        timelineEvents.push({
          id: `bid-${bid.id}`,
          type: 'bid_placed',
          title: 'Bid Received',
          description: `New proposal submitted for $${bid.amount}`, // TODO: Add currency field
          timestamp: bid.createdAt.toISOString(),
          actor: `${bid.freelancer.profile?.firstName || ''} ${bid.freelancer.profile?.lastName || ''}`.trim() || 'Unknown Freelancer',
          actorRole: 'freelancer'
        });

        if (bid.status === 'ACCEPTED') {
          timelineEvents.push({
            id: `bid-accepted-${bid.id}`,
            type: 'bid_accepted',
            title: 'Proposal Accepted',
            description: 'Client accepted the proposal and project started',
            timestamp: bid.updatedAt.toISOString(), // TODO: Add acceptedAt field when available
            actor: `${project.client.profile?.firstName || ''} ${project.client.profile?.lastName || ''}`.trim() || 'Unknown Client',
            actorRole: 'client'
          });
        }
      });

      // TODO: Re-enable when projectMilestone model is available
      // const milestones = await prisma.projectMilestone.findMany({
      //   where: { projectId: projectId },
      //   orderBy: { createdAt: 'asc' }
      // });
      // milestones.forEach(milestone => {
      //   if (milestone.status === 'completed') {
      //     const acceptedBid = project.bids.find(bid => bid.status === 'ACCEPTED');
      //     const freelancerName = acceptedBid ? `${acceptedBid.freelancer.profile?.firstName || ''} ${acceptedBid.freelancer.profile?.lastName || ''}`.trim() : 'Unknown Freelancer';
      //     timelineEvents.push({
      //       id: `milestone-${milestone.id}`,
      //       type: 'milestone_completed',
      //       title: `${milestone.title} Completed`,
      //       description: milestone.description || 'Milestone completed successfully',
      //       timestamp: milestone.completedAt?.toISOString() || milestone.updatedAt.toISOString(),
      //       actor: freelancerName,
      //       actorRole: 'freelancer'
      //     });
      //   }
      // });

      // TODO: Re-enable when projectCancellation model is available
      // if (project.status === 'CANCELLED') {
      //   const cancellation = await prisma.projectCancellation.findFirst({
      //     where: { projectId: projectId }
      //   });
      //   if (cancellation) {
      //     const acceptedBid = project.bids.find(bid => bid.status === 'ACCEPTED');
      //     const cancelledByUser = cancellation.cancelledBy === 'freelancer' && acceptedBid ? acceptedBid.freelancer : project.client;
      //     const actorName = cancelledByUser.profile ? `${cancelledByUser.profile.firstName || ''} ${cancelledByUser.profile.lastName || ''}`.trim() : 'Unknown User';
      //     timelineEvents.push({
      //       id: `cancelled-${cancellation.id}`,
      //       type: 'cancelled',
      //       title: 'Project Cancelled',
      //       description: `Project was cancelled. Reason: ${cancellation.reason}`,
      //       timestamp: cancellation.cancelledAt?.toISOString() || cancellation.createdAt.toISOString(),
      //       actor: actorName,
      //       actorRole: cancellation.cancelledBy
      //     });
      //   }
      // }

      // Sort events by timestamp
      timelineEvents.sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());

      return NextResponse.json({
        success: true,
        data: timelineEvents
      });

    } catch (dbError) {
      console.error('Database query error:', dbError);
      
      // Return mock timeline events when database is not ready
      const mockEvents = [
        {
          id: '1',
          type: 'created',
          title: 'Project Created',
          description: 'Project was posted and is now accepting bids',
          timestamp: '2024-06-03T15:34:00Z',
          actor: 'Esther Howard',
          actorRole: 'client'
        },
        {
          id: '2',
          type: 'bid_placed',
          title: 'Bid Received',
          description: 'New proposal submitted for €2000',
          timestamp: '2024-06-04T10:15:00Z',
          actor: 'John Developer',
          actorRole: 'freelancer'
        },
        {
          id: '3',
          type: 'bid_accepted',
          title: 'Proposal Accepted',
          description: 'Client accepted the proposal and project started',
          timestamp: '2024-06-05T14:20:00Z',
          actor: 'Esther Howard',
          actorRole: 'client'
        },
        {
          id: '4',
          type: 'milestone_completed',
          title: 'Initial Setup Completed',
          description: 'Project setup and environment configuration finished',
          timestamp: '2024-06-08T16:45:00Z',
          actor: 'John Developer',
          actorRole: 'freelancer'
        },
        {
          id: '5',
          type: 'cancelled',
          title: 'Project Cancelled',
          description: 'Project was cancelled due to scope changes',
          timestamp: '2024-06-15T14:30:00Z',
          actor: 'Esther Howard',
          actorRole: 'client'
        },
        {
          id: '6',
          type: 'refund_requested',
          title: 'Refund Requested',
          description: 'Client requested a refund of €1500',
          timestamp: '2024-06-15T14:35:00Z',
          actor: 'Esther Howard',
          actorRole: 'client'
        },
        {
          id: '7',
          type: 'refund_processed',
          title: 'Refund Processed',
          description: 'Refund of €1500 has been processed successfully',
          timestamp: '2024-06-16T10:15:00Z',
          actor: 'System',
          actorRole: 'system'
        }
      ];

      return NextResponse.json({
        success: true,
        data: mockEvents
      });
    }

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