import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/libs/prisma'
import { SUITABLE_HEAD_CODE, type Suitable } from '@/types/Suitable'

export async function GET(request: NextRequest) {
  try {
    const searchParams = request.nextUrl.searchParams
    const category = searchParams.get('category')
    const keyword = searchParams.get('keyword')

    const whereCondition: string[] = []
    const params: string[] = []
    if (category) {
      whereCondition.push(`${SUITABLE_HEAD_CODE.ROOF_MT_CD} = @P1`)
      params.push(category)
    }
    if (keyword) {
      whereCondition.push('PRODUCT_NAME LIKE @P2')
      params.push(`%${keyword}%`)
    }

    const startTime = performance.now()
    console.log(`쿼리 시작 시간: ${startTime}ms`)

    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
          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 1=1
    ORDER BY msm.product_name`

    // 검색 조건 추가
    if (whereCondition.length > 0) {
      query = query.replace('-- WHERE 1=1', `WHERE ${whereCondition.join(' AND ')}`)
    }

    // @ts-ignore
    const suitable: Suitable[] = await prisma.$queryRawUnsafe(query, ...params)

    const endTime = performance.now()
    console.log(`쿼리 실행 시간: ${endTime - startTime}ms`)

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