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

interface RefundRequest {
  action: 'request' | 'approve' | 'reject';
  amount?: number;
  reason?: string;
}

export async function POST(
  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;
    const body: RefundRequest = await req.json();
    const { action, amount, reason } = body;

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

    if (!action) {
      return NextResponse.json(
        { error: 'Action is required' },
        { status: 400 }
      );
    }

    try {
      // TODO: Re-enable when projectCancellation model is available
      // const project = await prisma.project.findFirst({
      //   where: {
      //     id: projectId,
      //     status: 'CANCELLED',
      //     OR: [
      //       { clientId: session.user.email },
      //       {
      //         bids: {
      //           some: {
      //             freelancerId: session.user.email,
      //             status: 'ACCEPTED'
      //           }
      //         }
      //       }
      //     ]
      //   },
      //   include: {
      //     cancellation: true,
      //     client: {
      //       select: {
      //         id: true,
      //         email: true,
      //         profile: {
      //           select: {
      //             firstName: true,
      //             lastName: true
      //           }
      //         }
      //       }
      //     },
      //     bids: {
      //       where: {
      //         status: 'ACCEPTED'
      //       },
      //       include: {
      //         freelancer: {
      //           select: {
      //             id: true,
      //             email: true,
      //             profile: {
      //               select: {
      //                 firstName: true,
      //                 lastName: true
      //               }
      //             }
      //           }
      //         }
      //       }
      //     }
      //   }
      // });

      // Mock response based on action
      const currentDate = new Date();
      
      switch (action) {
        case 'request':
          return NextResponse.json({
            success: true,
            message: 'Refund request submitted successfully',
            data: {
              refundId: `refund-${Date.now()}`,
              amount: amount || 1600, // Mock default refund amount
              status: 'pending',
              requestedAt: currentDate.toISOString(),
              estimatedProcessingTime: '3-5 business days'
            }
          });

        case 'approve':
          return NextResponse.json({
            success: true,
            message: 'Refund approved successfully',
            data: {
              refundId: `refund-${Date.now()}`,
              amount: amount || 1600,
              status: 'approved',
              approvedAt: currentDate.toISOString(),
              processingStarted: true
            }
          });

        case 'reject':
          return NextResponse.json({
            success: true,
            message: 'Refund request rejected',
            data: {
              refundId: `refund-${Date.now()}`,
              status: 'rejected',
              rejectedAt: currentDate.toISOString(),
              reason: reason || 'No reason provided'
            }
          });

        default:
          return NextResponse.json(
            { error: 'Invalid action. Must be request, approve, or reject' },
            { status: 400 }
          );
      }

    } catch (dbError) {
      console.error('Database error during refund processing:', dbError);
      
      // Return mock success response when database is not available
      return NextResponse.json({
        success: true,
        message: `Refund ${action} request received (database not available)`,
        data: {
          refundId: `refund-${Date.now()}`,
          amount: amount || 1600,
          status: action === 'request' ? 'pending' : action === 'approve' ? 'approved' : 'rejected',
          processedAt: new Date().toISOString()
        }
      });
    }

  } catch (error) {
    console.error('Error processing refund request:', error);
    
    return NextResponse.json(
      { 
        error: error instanceof Error ? error.message : 'Failed to process refund request',
        type: 'server_error'
      },
      { status: 500 }
    );
  }
}

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 {
      // TODO: Re-enable when projectCancellation model is available
      // Get refund status for cancelled project
      // const project = await prisma.project.findFirst({
      //   where: {
      //     id: projectId,
      //     status: 'CANCELLED',
      //     OR: [
      //       { clientId: session.user.email },
      //       {
      //         bids: {
      //           some: {
      //             freelancerId: session.user.email,
      //             status: 'ACCEPTED'
      //           }
      //         }
      //       }
      //     ]
      //   },
      //   include: {
      //     cancellation: true
      //   }
      // });

      // Return mock refund status
      const mockRefund = {
        projectId: projectId,
        refundAmount: 1600,
        refundStatus: 'pending',
        requestedAt: '2024-06-15T14:35:00Z',
        approvedAt: null,
        processedAt: null,
        reason: 'Project scope changed significantly',
        estimatedProcessingTime: '3-5 business days',
        notes: 'Refund request is being reviewed by our team'
      };

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

    } catch (dbError) {
      console.error('Database query error:', dbError);
      
      // Return mock refund status when database is not ready
      const mockRefund = {
        projectId: projectId,
        refundAmount: 1600,
        refundStatus: 'not_requested',
        requestedAt: null,
        approvedAt: null,
        processedAt: null,
        reason: null,
        estimatedProcessingTime: '3-5 business days',
        notes: 'No refund request has been made for this project'
      };

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

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