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

/**
 * @api {GET} /api/qna/list 문의 목록 조회 API
 * @apiName GET /api/qna/list
 * @apiGroup Qna
 * @apiDescription 문의 목록 조회 API
 *
 * @apiParam {String} compCd 회사 코드
 * @apiParam {String} langCd 언어 코드
 * @apiParam {String} storeId 판매점 ID
 * @apiParam {String} siteTpCd 사이트 유형 코드
 * @apiParam {String} schTitle 검색 제목
 * @apiParam {String} schRegId 검색 등록자 ID
 * @apiParam {String} schFromDt 검색 시작 일자
 * @apiParam {String} schToDt 검색 종료 일자
 * @apiParam {String} schAnswerYn 검색 답변 여부
 * @apiParam {String} loginId 로그인 ID
 *
 * @apiExample {curl} Example usage:
 *     curl -X GET http://localhost:3000/api/qna/list
 *
 * @apiSuccessExample {json} Success-Response:
 *     {
 *  "data": [
        {
            "totCnt": 1,
            "rowNumber": 1,
            "compCd": "5200",
            "qnaNo": 51,
            "qstTitle": "Q.CAST TEST22",
            "regDt": "2025.05.12",
            "regId": "X112",
            "regNm": "株式会社アイ工務店",
            "answerYn": "N",
            "attachYn": null,
            "qnaClsLrgCd": "見積関連",
            "qnaClsMidCd": "構造設置可否",
            "qnaClsSmlCd": "C05 未定2",
            "regUserNm": "Test"
        },
        ...
    ],
}
 * @apiError {Number} 500 서버 오류
 * @apiError {Number} 401 세션 정보 없음 (로그인 필요)
 */
async function getQnaList(request: Request): Promise<NextResponse> {
  const cookieStore = await cookies()
  const session = await getIronSession<SessionData>(cookieStore, sessionOptions)

  const service = new QnaService(session)

  const { searchParams } = new URL(request.url)
  const params = service.getSearchParams(searchParams)

  const result = await service.tryFunction(() => axios.get(`${process.env.NEXT_PUBLIC_INQUIRY_API_URL}/api/qna/list?${queryStringFormatter(params)}`), true)
  if (result instanceof ApiError) {
    return NextResponse.json({ error: result.message }, { status: result.statusCode })
  }
  return NextResponse.json(result.data.data)
}

export const GET = loggerWrapper(getQnaList)
