import { auth } from '@clerk/nextjs/server'
import { NextResponse } from 'next/server'
import { getDatabase, DatabaseFactory } from '@/lib/database'
import { ensureUserSynced } from '@/lib/sync-user'
import fs from 'fs'
import path from 'path'

const BACKUP_DIR = path.join(process.cwd(), 'backups')
const DB_PATH = path.join(process.cwd(), 'data', 'fitai.db')

export async function POST(req: Request) {
    try {
        const { userId } = await auth()
        if (!userId) return new NextResponse('Unauthorized', { status: 401 })

        const db = await getDatabase()
        const user = await ensureUserSynced(userId, db)

        if (!user || (user.role !== 'admin' && user.role !== 'superAdmin')) {
            return new NextResponse('Forbidden', { status: 403 })
        }

        const { filename } = await req.json()
        if (!filename) {
            return new NextResponse('Filename is required', { status: 400 })
        }

        const backupPath = path.join(BACKUP_DIR, filename)
        if (!fs.existsSync(backupPath)) {
            return new NextResponse('Backup file not found', { status: 404 })
        }

        // Close existing connection
        await DatabaseFactory.disconnect()

        // Restore file
        fs.copyFileSync(backupPath, DB_PATH)

        // Re-initialize connection (will happen automatically on next getDatabase call, but good to verify)
        await getDatabase()

        return NextResponse.json({ success: true })
    } catch (error) {
        console.error('Restore backup error:', error)
        return new NextResponse('Internal Server Error', { status: 500 })
    }
}
