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

/**
 * @api {GET} /api/submission 제출 대상 조회
 * @apiName GET /api/submission
 * @apiGroup Submission
 * @apiDescription 제출 대상 조회
 *
 * @param {String} storeId 판매점 ID (required)
 * @param {String} role 권한 (required)
 *
 * @apiSuccess {Object} data 제출 대상 목록
 * @apiSuccess {String} data.targetStoreId 판매점 ID
 * @apiSuccess {String} data.salesOfficeCd 영업소 코드
 * @apiSuccess {String} data.fromEmail 발신자 이메일
 * @apiSuccess {String} data.toEmail 수신자 이메일
 *
 * @returns {Promise<SubmitTargetResponse[]>} 제출 대상 목록
 * @apiSuccessExample {json} Success-Response:
 *     {
 *       "data": [
 *         {
 *           "targetStoreId": "1234567890",
 *           "salesOfficeCd": "1234567890",
 *           "fromEmail": "1234567890",
 *           "toEmail": "1234567890"
 *         }
 *       ]
 *     }
 *
 * @apiExample {curl} Example usage:
 *     curl -X GET \
 *       -H "Content-Type: application/json" \
 *       http://localhost:3000/api/submission?storeId=1234567890&role=admin
 *
 * @apiError {Object} error 에러 객체
 * @apiError {String} error.message 에러 메시지
 */
async function getSubmitTargetData(request: NextRequest): Promise<NextResponse> {
  const { searchParams } = new URL(request.url)
  const storeId = searchParams.get('storeId')
  const role = searchParams.get('role')

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

  const submissionService = new SubmissionService(storeId, role)
  const result = await submissionService.tryFunction(() => submissionService.getSubmissionTarget())
  if (result instanceof ApiError) {
    return NextResponse.json({ error: result.message }, { status: result.statusCode })
  }
  return NextResponse.json(result)
}

export const GET = loggerWrapper(getSubmitTargetData)
