// SvelteKit server routes for Dropbox integration
// For a private module, you would import from your private registry or local path
// import { createSvelteKitHandlers } from '@yourcompany/dropbox-sync';
import { createSvelteKitHandlers } from 'dropbox-sync'
import { Server } from 'socket.io'
import type { RequestEvent } from '@sveltejs/kit'

// Create all the route handlers
export const handlers = createSvelteKitHandlers()

// Status endpoint handler
export async function handleStatus(event: RequestEvent) {
    return handlers.status({ cookies: event.cookies })
}

// OAuth start endpoint handler
export async function handleOAuthStart() {
    return handlers.oauthStart()
}

// OAuth callback endpoint handler
export async function handleOAuthCallback(event: RequestEvent) {
    return handlers.oauthCallback({
        url: new URL(event.request.url),
        cookies: event.cookies,
    })
}

// Logout endpoint handler
export async function handleLogout(event: RequestEvent) {
    return handlers.logout({ cookies: event.cookies })
}

// Setup Socket.IO for SvelteKit
let io: Server

export function getSocketIO(server: any) {
    if (!io) {
        io = new Server(server)

        io.on('connection', (socket) => {
            console.log('Client connected:', socket.id)

            // Handle sync start request
            socket.on('dropbox:sync', async () => {
                try {
                    // In a real implementation, this would use the server-side Dropbox client
                    // to perform the actual sync

                    // Emit queue information
                    socket.emit('sync:queue', {
                        total: 8,
                        totalUploads: 3,
                        totalDownloads: 5,
                    })

                    // Simulate sync process with progress updates
                    let progress = 0
                    const interval = setInterval(() => {
                        progress += 12.5 // 8 total files, so each is 12.5%

                        if (progress <= 100) {
                            socket.emit('sync:progress', {
                                progress,
                                message: `Processing files... ${Math.round(
                                    progress
                                )}%`,
                                type: progress < 50 ? 'upload' : 'download',
                            })
                        }

                        if (progress >= 100) {
                            clearInterval(interval)
                            socket.emit('sync:complete', {
                                message: 'Sync completed successfully',
                                stats: {
                                    uploaded: 3,
                                    downloaded: 5,
                                },
                            })
                        }
                    }, 600)

                    // Store the interval for cancellation
                    socket.data.syncInterval = interval
                } 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', () => {
                if (socket.data.syncInterval) {
                    clearInterval(socket.data.syncInterval)
                    delete socket.data.syncInterval
                }

                socket.emit('sync:complete', {
                    message: 'Sync cancelled by user',
                })
            })

            // Handle disconnect
            socket.on('disconnect', () => {
                console.log('Client disconnected:', socket.id)

                // Clean up any ongoing operations
                if (socket.data.syncInterval) {
                    clearInterval(socket.data.syncInterval)
                }
            })
        })
    }

    return io
}
