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

type RouteParams = { params: Promise<{ key: string }> }

/**
 * GET /api/v1/admin/settings/{key}
 * Get a single setting value
 */
export async function GET(request: NextRequest, { params }: RouteParams) {
  try {
    const session = await auth()

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

    const { key } = await params

    if (!(key in SETTING_KEYS)) {
      return NextResponse.json(
        { error: `Unknown setting key: ${key}` },
        { status: 400 }
      )
    }

    const config = SETTING_KEYS[key as SettingKey]
    const value = await settingsService.get(key as SettingKey)

    // Don't return actual encrypted values via individual get
    if (config.encrypted && value) {
      return NextResponse.json({
        key,
        hasValue: true,
        encrypted: true,
        category: config.category,
      })
    }

    return NextResponse.json({
      key,
      value: value || '',
      hasValue: !!value,
      encrypted: config.encrypted,
      category: config.category,
    })
  } catch (error) {
    console.error('Error getting setting:', error)
    return NextResponse.json(
      { error: 'Failed to get setting' },
      { status: 500 }
    )
  }
}

/**
 * PUT /api/v1/admin/settings/{key}
 * Update a single setting
 */
export async function PUT(request: NextRequest, { params }: RouteParams) {
  try {
    const session = await auth()

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

    const { key } = await params

    if (!(key in SETTING_KEYS)) {
      return NextResponse.json(
        { error: `Unknown setting key: ${key}` },
        { status: 400 }
      )
    }

    const body = await request.json()
    const { value } = body as { value: string }

    if (value === undefined) {
      return NextResponse.json(
        { error: 'Value is required' },
        { status: 400 }
      )
    }

    await settingsService.set(key as SettingKey, value)

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

/**
 * DELETE /api/v1/admin/settings/{key}
 * Remove a setting (revert to default)
 */
export async function DELETE(request: NextRequest, { params }: RouteParams) {
  try {
    const session = await auth()

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

    const { key } = await params

    if (!(key in SETTING_KEYS)) {
      return NextResponse.json(
        { error: `Unknown setting key: ${key}` },
        { status: 400 }
      )
    }

    const deleted = await settingsService.delete(key as SettingKey)

    if (deleted) {
      return NextResponse.json({
        message: 'Setting removed (reverted to default)',
        key,
      })
    } else {
      return NextResponse.json({
        message: 'Setting was not set',
        key,
      })
    }
  } catch (error) {
    console.error('Error deleting setting:', error)
    return NextResponse.json(
      { error: 'Failed to delete setting' },
      { status: 500 }
    )
  }
}
