import { NextRequest, NextResponse } from 'next/server'
import { HttpStatusCode } from 'axios'
import { loggerWrapper } from '@/libs/api-wrapper'
import { prisma } from '@/libs/prisma'
import { Suitable } from '@/types/Suitable'

/**
 * @api {post} /api/suitable 지붕재 적합성 데이터 모든 컬럼 조회 API
 * @apiName GetSuitable
 * @apiGroup Suitable
 *
 * @apiDescription
 * 지붕재 적합성 데이터의 모든 컬럼을 조회
 *
 * @apiBody {FormData} form-data
 * @apiBody {String} form-data.ids 메인 ID 목록 (쉼표로 구분된 문자열)
 * @apiBody {String} [form-data.detailIds] 상세 ID 목록 (쉼표로 구분된 문자열)
 *
 * @apiExample {curl} Example usage:
 *     curl -X POST \
 *       -F "ids=1,2,3" \
 *       -F "detailIds=4,5,6" \
 *       http://localhost:3000/api/suitable
 *
 * @apiSuccess {Array} suitable 지붕재 적합성 데이터
 * @apiSuccessExample {json} Success-Response:
 *     [
 *       {
 *         "id": 1,
 *         "product_name": "test",
 *         "manu_ft_cd": "test",
 *         "roof_mt_cd": "test",
 *         "roof_sh_cd": "test",
 *         "detail": [
 *           {
 *             "id": 1,
 *             "trestle_mfpc_cd": "MFPC001",
 *             "trestle_manufacturer_product_name": "test",
 *             "memo": "test"
 *           }
 *         ]
 *       }
 *     ]
 */
async function getSuitable(request: NextRequest): Promise<NextResponse> {
  try {
    const body: Record<string, string> = await request.json()
    const ids = body.ids
    const detailIds = body.detailIds || ''

    /* 파라미터 체크 */
    if (ids === '') {
      return NextResponse.json({ error: '필수 파라미터가 누락되었습니다' }, { status: HttpStatusCode.BadRequest })
    }

    let query = `
    SELECT 
      msm.id
      , msm.product_name
      , msm.manu_ft_cd
      , msm.roof_mt_cd
      , msm.roof_sh_cd
      , details.detail
    FROM ms_suitable_main msm
    LEFT JOIN (
      SELECT
        msd.main_id
        , (
          SELECT
            msd_json.id
            , msd_json.trestle_mfpc_cd
            , msd_json.trestle_manufacturer_product_name
            , msd_json.memo
          FROM ms_suitable_detail msd_json
            WHERE msd.main_id = msd_json.main_id
              --detailIds AND msd_json.id IN (:detailIds)
          FOR JSON PATH
        ) AS detail
      FROM ms_suitable_detail msd
      GROUP BY msd.main_id
    ) AS details 
      ON msm.id = details.main_id 
        AND details.main_id IN (:mainIds)
    WHERE
      msm.id IN (:mainIds)
    ORDER BY msm.product_name;
    `

    /* 검색 조건 설정 */
    query = query.replaceAll(':mainIds', ids)
    if (detailIds) {
      query = query.replace('--detailIds ', '')
      query = query.replace(':detailIds', detailIds)
    }

    const suitable: Suitable[] = await prisma.$queryRawUnsafe(query)

    return NextResponse.json(suitable)
  } catch (error) {
    console.error(`데이터 조회 중 오류가 발생했습니다: ${error}`)
    return NextResponse.json({ error: `데이터 조회 중 오류가 발생했습니다: ${error}` }, { status: HttpStatusCode.InternalServerError })
  }
}

export const POST = loggerWrapper(getSuitable)
