// Example Next.js API routes implementation
import { createNextDropboxApiHandlers, handleOAuthCallback } from 'dropbox-sync'
import { Server } from 'socket.io'
import type { NextApiRequest, NextApiResponse } from 'next'

// Create the API handlers
const dropboxHandlers = createNextDropboxApiHandlers()

// Status endpoint
export async function GET_status() {
    return dropboxHandlers.status()
}

// OAuth start endpoint
export async function GET_oauthStart() {
    return dropboxHandlers.oauthStart()
}

// OAuth callback endpoint
export async function GET_oauthCallback(req: Request) {
    return handleOAuthCallback(req)
}

// Logout endpoint
export async function POST_logout() {
    return dropboxHandlers.logout()
}

// Socket.IO setup for App Router in Next.js 13+
let io: Server

export async function setupSocketIO(res: NextApiResponse) {
    if (!io) {
        // @ts-ignore - NextApiResponse is compatible but TypeScript doesn't know
        const httpServer = res.socket?.server

        if (httpServer && !httpServer.io) {
            io = new Server(httpServer)
            httpServer.io = io

            // Handle Dropbox sync events
            io.on('connection', (socket) => {
                console.log('Client connected:', socket.id)

                // Handle sync start request
                socket.on('dropbox:sync', async () => {
                    try {
                        // Emit queue information
                        socket.emit('sync:queue', {
                            total: 10, // This would be dynamic in real implementation
                            totalUploads: 5,
                            totalDownloads: 5,
                        })

                        // Simulate sync process (in real app, this would use the Dropbox client)
                        let progress = 0
                        const interval = setInterval(() => {
                            progress += 10

                            if (progress <= 100) {
                                socket.emit('sync:progress', {
                                    progress,
                                    message: `Processing files... ${progress}%`,
                                    type:
                                        progress % 20 === 0
                                            ? 'upload'
                                            : 'download',
                                })
                            }

                            if (progress >= 100) {
                                clearInterval(interval)
                                socket.emit('sync:complete', {
                                    message: 'Sync completed successfully',
                                    stats: {
                                        uploaded: 5,
                                        downloaded: 5,
                                    },
                                })
                            }
                        }, 500)
                    } catch (error: any) {
                        console.error('Error syncing with Dropbox:', error)
                        socket.emit('sync:error', {
                            message:
                                error.message ||
                                'An error occurred during sync',
                        })
                    }
                })

                // Handle sync cancel request
                socket.on('sync:cancel', () => {
                    console.log('Sync cancelled by client:', socket.id)
                    socket.emit('sync:complete', {
                        message: 'Sync cancelled by user',
                    })
                })

                // Handle disconnect
                socket.on('disconnect', () => {
                    console.log('Client disconnected:', socket.id)
                })
            })
        }
    }

    return res
}
