import config from '@payload-config'
import {
  REST_DELETE,
  REST_GET,
  REST_OPTIONS,
  REST_PATCH,
  REST_POST,
  REST_PUT,
} from '@payloadcms/next/routes'
import { NextRequest, NextResponse } from 'next/server'

export const runtime = 'nodejs'

const handlePost = REST_POST(config)

export async function POST(req: NextRequest) {
  const res = await handlePost(req, {
    params: Promise.resolve({
      slug: ['form-submissions'],
    }),
  })

  if (!res.ok) {
    return res
  }

  let message = 'Form Submission successfully created.'

  try {
    const body = (await res.json()) as { message?: string }
    if (body?.message) {
      message = body.message
    }
  } catch {
    // Ignore JSON parse errors and fall back to default message.
  }

  return NextResponse.json(
    {
      status: res.status,
      message,
    },
    {
      status: res.status,
      headers: new Headers(res.headers),
    },
  )
}

export const GET = REST_GET(config)
export const DELETE = REST_DELETE(config)
export const PATCH = REST_PATCH(config)
export const PUT = REST_PUT(config)
export const OPTIONS = REST_OPTIONS(config)
