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

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

    const ids = searchParams.get('ids')
    const detailIds = searchParams.get('subIds')

    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 
        --ids AND details.main_id IN (:mainIds)
        --detailIds AND details.id IN (:detailIds)
    WHERE 1=1
      --ids AND msm.id IN (:mainIds)
    ORDER BY msm.product_name;
    `

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

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

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

