import { auth } from '@clerk/nextjs/server'
import { NextResponse } from 'next/server'
import { getDatabase } 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 GET() {
    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 })
        }

        if (!fs.existsSync(BACKUP_DIR)) {
            fs.mkdirSync(BACKUP_DIR, { recursive: true })
        }

        const files = fs.readdirSync(BACKUP_DIR)
            .filter(file => file.endsWith('.db'))
            .map(file => {
                const stats = fs.statSync(path.join(BACKUP_DIR, file))
                return {
                    name: file,
                    size: stats.size,
                    createdAt: stats.birthtime
                }
            })
            .sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime())

        return NextResponse.json(files)
    } catch (error) {
        console.error('List backups error:', error)
        return new NextResponse('Internal Server Error', { status: 500 })
    }
}

export async function POST() {
    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 })
        }

        if (!fs.existsSync(BACKUP_DIR)) {
            fs.mkdirSync(BACKUP_DIR, { recursive: true })
        }

        const timestamp = new Date().toISOString().replace(/[:.]/g, '-')
        const backupPath = path.join(BACKUP_DIR, `backup-${timestamp}.db`)

        // Ensure source DB exists
        if (!fs.existsSync(DB_PATH)) {
            return new NextResponse('Database file not found', { status: 404 })
        }

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

        return NextResponse.json({ success: true, filename: `backup-${timestamp}.db` })
    } catch (error) {
        console.error('Create backup error:', error)
        return new NextResponse('Internal Server Error', { status: 500 })
    }
}
