import { NextRequest, NextResponse } from 'next/server'
import { z } from 'zod'
import { AdminApiError, requireAdminForApi } from '@/lib/admin-auth'
import { applyRuntimeSettingsToShops, updateRuntimeSettings } from '@/lib/admin-data'
import { logAdminAction } from '@/lib/audit'

const schema = z.object({
  app_name: z.string().trim().min(1).max(120),
  business_name: z.string().trim().min(1).max(120),
  website_url: z.string().max(255).default(''),
  support_email: z.string().max(255).default(''),
  support_phone: z.string().max(60).default(''),
  support_whatsapp: z.string().max(60).default(''),
  wave_number: z.string().max(60).default(''),
  orange_money_number: z.string().max(60).default(''),
  subscription_price_fcfa: z.number().int().min(0).max(100000000),
  payment_instructions: z.string().max(5000).default(''),
})

export async function POST(request: NextRequest) {
  try {
    const admin = await requireAdminForApi()
    const body = schema.parse(await request.json())
    const runtime = await updateRuntimeSettings(body)
    const result = await applyRuntimeSettingsToShops(runtime)

    await logAdminAction({
      adminUserId: admin.userId,
      action: 'apply_runtime_settings_to_shops',
      targetType: 'runtime_settings',
      targetId: runtime.key,
      metadata: { updated: result.updated },
    })

    return NextResponse.json({
      message: `Configuration appliquée à ${result.updated} boutique(s).`,
      updated: result.updated,
    })
  } catch (error) {
    if (error instanceof AdminApiError) {
      return NextResponse.json({ error: error.message }, { status: error.status })
    }
    if (error instanceof z.ZodError) {
      return NextResponse.json({ error: error.issues[0]?.message ?? 'Invalid payload' }, { status: 400 })
    }
    console.error(error)
    return NextResponse.json({ error: 'Unexpected error' }, { status: 500 })
  }
}
