import { type NextRequest, NextResponse } from "next/server"
import { applicationDb } from "@/lib/db"
import type { ApiResponse } from "@/lib/types"

// Handle file uploads
export async function POST(request: NextRequest) {
  try {
    // Get user ID from session cookie (simplified)
    const sessionCookie = request.cookies.get("session")
    if (!sessionCookie) {
      return NextResponse.json<ApiResponse>(
        {
          success: false,
          error: "Not authenticated",
        },
        { status: 401 },
      )
    }

    const session = JSON.parse(sessionCookie.value)
    const userId = session.userId

    const formData = await request.formData()
    const file = formData.get("file") as File
    const category = formData.get("category") as string

    if (!file || !category) {
      return NextResponse.json<ApiResponse>(
        {
          success: false,
          error: "File and category are required",
        },
        { status: 400 },
      )
    }

    // Validate file size (5MB max)
    if (file.size > 5 * 1024 * 1024) {
      return NextResponse.json<ApiResponse>(
        {
          success: false,
          error: "File size must be less than 5MB",
        },
        { status: 400 },
      )
    }

    // Validate file type
    const allowedTypes = [
      "application/pdf",
      "application/msword",
      "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
      "image/jpeg",
      "image/jpg",
      "image/png",
    ]

    if (!allowedTypes.includes(file.type)) {
      return NextResponse.json<ApiResponse>(
        {
          success: false,
          error: "Invalid file type. Only PDF, DOC, DOCX, JPG, and PNG files are allowed",
        },
        { status: 400 },
      )
    }

    // In a real app, you would:
    // 1. Upload file to cloud storage (AWS S3, Cloudinary, etc.)
    // 2. Generate secure URL
    // 3. Store file metadata in database

    // For now, we'll simulate the upload
    const fileId = `file_${Date.now()}`
    const fileUrl = `/uploads/${userId}/${fileId}_${file.name}`

    const application = await applicationDb.findByUserId(userId)
    if (!application) {
      return NextResponse.json<ApiResponse>(
        {
          success: false,
          error: "Application not found",
        },
        { status: 404 },
      )
    }

    // Remove existing file for this category
    const updatedFiles = application.uploads.files.filter((f) => f.category !== category)

    // Add new file
    updatedFiles.push({
      id: fileId,
      name: file.name,
      size: file.size,
      type: file.type,
      category,
      uploaded: true,
      url: fileUrl,
    })

    // Update application
    await applicationDb.update(userId, {
      uploads: { files: updatedFiles },
    })

    return NextResponse.json<ApiResponse>({
      success: true,
      data: {
        fileId,
        name: file.name,
        category,
        url: fileUrl,
      },
      message: "File uploaded successfully",
    })
  } catch (error) {
    console.error("Upload error:", error)
    return NextResponse.json<ApiResponse>(
      {
        success: false,
        error: "Internal server error",
      },
      { status: 500 },
    )
  }
}
