import axios, { HttpStatusCode } from 'axios'
import { NextResponse } from 'next/server'
import { loggerWrapper } from '@/libs/api-wrapper'
import { QnaService } from '../service'
import { ApiError } from 'next/dist/server/api-utils'
import { getIronSession } from 'iron-session'
import { SessionData } from '@/types/Auth'
import { sessionOptions } from '@/libs/session'
import { cookies } from 'next/headers'
import { ERROR_MESSAGE } from '@/hooks/useAlertMsg'

/**
 * @api {POST} /api/qna/save 문의 저장 API
 * @apiName POST /api/qna/save
 * @apiGroup Qna
 * @apiDescription 문의 메일 발송 후 문의 저장 API
 *
 * @apiBody {FormData} formData 문의 저장 요청 파라미터
 *
 * @apiExample {curl} Example usage:
 *     curl -X POST http://localhost:3000/api/qna/save
 *
 * @apiSuccessExample {json} Success-Response:
 *     {
 *        "data" : {
 *          "cnt": 1,
 *          "qnoNo": 1,
 *          "mailYn": "Y"
 *          },
 *     },
 * @apiError {Number} 500 서버 오류
 */
async function setQna(request: Request): Promise<NextResponse> {
  const cookieStore = await cookies()
  const session = await getIronSession<SessionData>(cookieStore, sessionOptions)
  const service = new QnaService(session)

  const formData = await request.formData()
  const mailResult = await service.sendMail(formData)
  if (mailResult instanceof ApiError) {
    return NextResponse.json({ error: ERROR_MESSAGE.EMAIL_SEND_ERROR }, { status: HttpStatusCode.InternalServerError })
  }

  const result = await service.tryFunction(() =>
    axios.post(`${process.env.NEXT_PUBLIC_INQUIRY_API_URL}/api/qna/save`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    }),
  )
  if (result instanceof ApiError) {
    return NextResponse.json({ error: result.message }, { status: result.statusCode })
  }
  return NextResponse.json(result.data)
}

export const POST = loggerWrapper(setQna)
