import { HttpStatusCode } from 'axios'
import { NextResponse } from 'next/server'
import { loggerWrapper } from '@/libs/api-wrapper'
import { ERROR_MESSAGE } from '@/hooks/useAlertMsg'
import { QnaService } from '../service'
import { ApiError } from 'next/dist/server/api-utils'

/**
 * @api {GET} /api/qna/file 문의 첨부 파일 다운로드 API
 * @apiName GET /api/qna/file
 * @apiGroup Qna
 * @apiDescription 문의 첨부 파일 다운로드 API
 *
 * @apiParam {String} encodeFileNo 인코딩 파일 번호
 * @apiParam {String} srcFileNm 소스 파일 이름
 *
 * @apiExample {curl} Example usage:
 *     curl -X GET http://localhost:3000/api/qna/file?encodeFileNo=1234567890&srcFileNm=test.pdf
 *
 * @apiSuccessExample {octet-stream} Success-Response:
 *     file content
 *
 * @apiError {Number} 500 서버 오류
 * @apiError {Number} 400 잘못된 요청
 */
async function downloadFile(request: Request): Promise<NextResponse> {
  const service = new QnaService()
  const { searchParams } = new URL(request.url)
  const encodeFileNo = searchParams.get('encodeFileNo')
  const srcFileNm = searchParams.get('srcFileNm') || 'downloaded-file'

  if (!encodeFileNo) {
    return NextResponse.json({ error: ERROR_MESSAGE.BAD_REQUEST }, { status: HttpStatusCode.BadRequest })
  }

  const url = `${process.env.NEXT_PUBLIC_INQUIRY_API_URL}/api/file/downloadFile2?encodeFileNo=${encodeFileNo}`

  const resp = await service.tryFunction(() => fetch(url), true)
  if (resp instanceof ApiError) {
    return NextResponse.json({ error: resp.message }, { status: resp.statusCode })
  }

  const contentType = resp.headers.get('content-type') || 'application/octet-stream'
  const contentDisposition = resp.headers.get('content-disposition') || `attachment; filename="${srcFileNm}"`

  return new NextResponse(resp.body, {
    status: 200,
    headers: {
      'Content-Type': contentType,
      'Content-Disposition': contentDisposition,
    },
  })
}

export const GET = loggerWrapper(downloadFile)
