import { NextRequest, NextResponse } from 'next/server'
import { auth } from '@/lib/auth'
import { settingsService, SETTING_KEYS, SettingKey } from '@/lib/services/settings-service'

/**
 * GET /api/v1/admin/settings
 * List all settings (with masked values for encrypted ones)
 */
export async function GET(request: NextRequest) {
  try {
    const session = await auth()

    if (!session || session.user.userType !== 'staff') {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    const searchParams = request.nextUrl.searchParams
    const category = searchParams.get('category')

    if (category) {
      const settings = await settingsService.getCategory(category)
      return NextResponse.json({ settings })
    }

    const settings = await settingsService.list()

    // Group by category for easier UI consumption
    const grouped: Record<string, typeof settings> = {}
    for (const setting of settings) {
      if (!grouped[setting.category]) {
        grouped[setting.category] = []
      }
      grouped[setting.category].push(setting)
    }

    return NextResponse.json({
      settings,
      grouped,
      categories: Object.keys(grouped).sort(),
    })
  } catch (error) {
    console.error('Error listing settings:', error)
    return NextResponse.json(
      { error: 'Failed to list settings' },
      { status: 500 }
    )
  }
}

/**
 * PUT /api/v1/admin/settings
 * Batch update settings
 */
export async function PUT(request: NextRequest) {
  try {
    const session = await auth()

    if (!session || session.user.userType !== 'staff') {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    const body = await request.json()
    const { settings } = body as { settings: Array<{ key: string; value: string }> }

    if (!settings || !Array.isArray(settings)) {
      return NextResponse.json(
        { error: 'Settings array is required' },
        { status: 400 }
      )
    }

    // Validate all keys
    for (const { key } of settings) {
      if (!(key in SETTING_KEYS)) {
        return NextResponse.json(
          { error: `Unknown setting key: ${key}` },
          { status: 400 }
        )
      }
    }

    // Filter out empty values for encrypted fields (don't overwrite with empty)
    const validSettings = settings.filter(({ key, value }) => {
      const config = SETTING_KEYS[key as SettingKey]
      // For encrypted fields, skip if value is empty (user didn't want to change it)
      if (config.encrypted && !value) {
        return false
      }
      return true
    }) as Array<{ key: SettingKey; value: string }>

    await settingsService.batchUpdate(validSettings)

    // Return updated settings
    const updatedSettings = await settingsService.list()

    return NextResponse.json({
      message: 'Settings updated successfully',
      settings: updatedSettings,
    })
  } catch (error) {
    console.error('Error updating settings:', error)
    return NextResponse.json(
      { error: 'Failed to update settings' },
      { status: 500 }
    )
  }
}
