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

const schema = z.object({
  price_fcfa: z.number().int().min(0).max(100000000),
  wave_number: z.string().max(60).default(''),
  orange_money_number: z.string().max(60).default(''),
  support_phone: z.string().max(60).default(''),
  support_whatsapp: z.string().max(60).default(''),
})

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

export async function PATCH(request: NextRequest, { params }: RouteParams) {
  try {
    const admin = await requireAdminForApi()
    const body = schema.parse(await request.json())
    const { shopId } = await params

    const billing = await updateShopBillingSettings(shopId, body)

    await logAdminAction({
      adminUserId: admin.userId,
      action: 'update_shop_billing_settings',
      targetType: 'shop',
      targetId: shopId,
      metadata: {
        price_fcfa: billing.price_fcfa,
        wave_number: billing.wave_number,
        orange_money_number: billing.orange_money_number,
        support_phone: billing.support_phone,
        support_whatsapp: billing.support_whatsapp,
      },
    })

    return NextResponse.json({
      message: 'Paramètres de facturation boutique mis à jour.',
      billing,
    })
  } 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 })
  }
}
