import { NextResponse } from 'next/server'
import fs from 'fs'
import path from 'path'
import { AppSettings } from '@/lib/types'

const SETTINGS_FILE = path.join(process.cwd(), 'server-settings.json')

const DEFAULT_SETTINGS: AppSettings = {
    telegram: {
        botToken: '',
        chatId: '',
    },
    aiProviders: [],
}

export async function GET() {
    try {
        if (!fs.existsSync(SETTINGS_FILE)) {
            return NextResponse.json(DEFAULT_SETTINGS)
        }
        const data = fs.readFileSync(SETTINGS_FILE, 'utf8')
        const settings = JSON.parse(data)
        return NextResponse.json(settings)
    } catch (error) {
        console.error('Error reading settings:', error)
        return NextResponse.json(DEFAULT_SETTINGS, { status: 500 })
    }
}

export async function POST(request: Request) {
    try {
        const body = await request.json()
        // Basic validation could go here
        const settings: AppSettings = {
            telegram: {
                botToken: body.telegram?.botToken || '',
                chatId: body.telegram?.chatId || ''
            },
            aiProviders: Array.isArray(body.aiProviders) ? body.aiProviders : []
        }

        fs.writeFileSync(SETTINGS_FILE, JSON.stringify(settings, null, 2))
        return NextResponse.json({ success: true, settings })
    } catch (error) {
        console.error('Error saving settings:', error)
        return NextResponse.json({ success: false, error: 'Failed to save settings' }, { status: 500 })
    }
}
