import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/libs/prisma'
import { SUITABLE_HEAD_CODE, type SuitableMain } 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')

    let MainWhereCondition: any = {}
    const whereCondition: string[] = []
    const params: string[] = []
    if (category) {
      whereCondition.push(`${SUITABLE_HEAD_CODE.ROOF_MT_CD} = @P1`)
      params.push(category)
      MainWhereCondition[SUITABLE_HEAD_CODE.ROOF_MT_CD] = category
    }
    if (keyword) {
      whereCondition.push('PRODUCT_NAME LIKE @P2')
      params.push(`%${keyword}%`)
      MainWhereCondition['PRODUCT_NAME'] = {
        contains: keyword,
      }
    }
    const startTime = performance.now()
    console.log(`쿼리 (main table) 시작 시간: ${startTime}ms`)

    // @ts-ignore
    const suitable = await prisma.MS_SUITABLE_MAIN.findMany({
      select: {
        ID: true,
        PRODUCT_NAME: true,
        ROOF_MT_CD: true,
      },
      where: MainWhereCondition,
      orderBy: {
        PRODUCT_NAME: 'asc',
      },
    })

    const endTime = performance.now()
    console.log(`쿼리 (main table) 종료 시간: ${endTime - startTime}ms`)

    const mainIds: number[] = suitable.map((item: SuitableMain) => item.id)


    const startTime2 = performance.now()
    console.log(`쿼리 (detail table) 시작 시간: ${startTime2}ms`)
    let detailQuery = `
    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
    -- WHERE 1=1
    GROUP BY msd.main_id
    `
    if (whereCondition.length > 0) {
      detailQuery = detailQuery.replace('-- WHERE 1=1', `WHERE msd.main_id IN @P1`)
    }
    // @ts-ignore
    const detail = await prisma.$queryRawUnsafe(detailQuery, ...mainIds)

    const endTime2 = performance.now()
    console.log(`쿼리 (detail table) 종료 시간: ${endTime2 - startTime2}ms`)

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

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