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,
          clientId: session.user.email
        }
      });

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

      // TODO: Get project documents when ProjectDocument model is available
      // Return mock documents for now
      const documents = [
        {
          id: 'doc1',
          fileName: 'Project Requirements.pdf',
          originalName: 'requirements.pdf',
          fileSize: '1.2 MB',
          fileType: 'application/pdf',
          fileUrl: '/mock/documents/requirements.pdf',
          uploadedBy: session.user?.email || 'client',
          createdAt: new Date()
        },
        {
          id: 'doc2',
          fileName: 'Design Mockups.zip',
          originalName: 'mockups.zip',
          fileSize: '5.8 MB',
          fileType: 'application/zip',
          fileUrl: '/mock/documents/mockups.zip',
          uploadedBy: session.user?.email || 'client',
          createdAt: new Date()
        }
      ];

      const formattedDocuments = documents.map(doc => ({
        id: doc.id,
        name: doc.fileName,
        originalName: doc.originalName,
        size: doc.fileSize,
        type: doc.fileType,
        url: doc.fileUrl,
        uploadedBy: doc.uploadedBy,
        createdAt: doc.createdAt.toISOString()
      }));

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

    } catch (dbError) {
      console.error('Database query error:', dbError);
      
      // Return mock documents when database is not ready
      const mockDocuments = [
        {
          id: '1',
          name: 'Project Brief.pdf',
          originalName: 'Project Brief.pdf',
          size: '2.5MB',
          type: 'pdf',
          url: '/documents/project-brief.pdf',
          uploadedBy: 'client',
          createdAt: new Date().toISOString()
        },
        {
          id: '2',
          name: 'Project Logo Blue.svg',
          originalName: 'Project Logo Blue.svg', 
          size: '145KB',
          type: 'svg',
          url: '/documents/logo-blue.svg',
          uploadedBy: 'client',
          createdAt: new Date().toISOString()
        },
        {
          id: '3',
          name: 'Stock Photos Guidelines Samples.png',
          originalName: 'Stock Photos Guidelines Samples.png',
          size: '8.2MB',
          type: 'png',
          url: '/documents/stock-photos.png',
          uploadedBy: 'client',
          createdAt: new Date().toISOString()
        },
        {
          id: '4',
          name: 'Project Brief.pdf',
          originalName: 'Project Brief Copy.pdf',
          size: '2.5MB',
          type: 'pdf', 
          url: '/documents/project-brief-copy.pdf',
          uploadedBy: 'client',
          createdAt: new Date().toISOString()
        },
        {
          id: '5',
          name: 'Stock Videos Guidelines Samples.mp4',
          originalName: 'Stock Videos Guidelines Samples.mp4',
          size: '256MB',
          type: 'video',
          url: '/documents/stock-videos.mp4',
          uploadedBy: 'client',
          createdAt: new Date().toISOString()
        },
        {
          id: '6',
          name: 'Project Logo Blue.svg',
          originalName: 'Project Logo Blue Copy.svg',
          size: '145KB', 
          type: 'svg',
          url: '/documents/logo-blue-copy.svg',
          uploadedBy: 'client',
          createdAt: new Date().toISOString()
        }
      ];

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

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

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 = await req.json();
    const { fileName, originalName, fileSize, fileType, fileUrl } = body;

    // Validate required fields
    if (!fileName || !originalName || !fileSize || !fileType || !fileUrl) {
      return NextResponse.json(
        { error: 'All document fields are required' },
        { status: 400 }
      );
    }

    try {
      // Verify user has access to this project
      const project = await prisma.project.findFirst({
        where: {
          id: projectId,
          clientId: session.user.email
        }
      });

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

      // TODO: Create document record when ProjectDocument model is available
      // Return mock document for now
      const document = {
        id: `doc-${Date.now()}`,
        projectId,
        fileName,
        originalName,
        fileSize,
        fileType,
        fileUrl,
        uploadedBy: session.user?.email || 'unknown',
        createdAt: new Date(),
        updatedAt: new Date()
      };

      return NextResponse.json({
        success: true,
        message: 'Document uploaded successfully',
        data: {
          id: document.id,
          name: document.fileName,
          originalName: document.originalName,
          size: document.fileSize,
          type: document.fileType,
          url: document.fileUrl,
          uploadedBy: document.uploadedBy,
          createdAt: document.createdAt.toISOString()
        }
      });

    } catch (dbError) {
      console.error('Database error during document upload:', dbError);
      
      // Return mock success response when database is not available
      return NextResponse.json({
        success: true,
        message: 'Document uploaded successfully (database not available)',
        data: {
          id: `doc-${Date.now()}`,
          name: fileName,
          originalName,
          size: fileSize,
          type: fileType,
          url: fileUrl,
          uploadedBy: session.user.email,
          createdAt: new Date().toISOString()
        }
      });
    }

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