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

    let query = `
    SELECT 
      msm.id
      , details.detail_id
    FROM ms_suitable_main msm
    LEFT JOIN (
      SELECT
        msd.main_id
        , STRING_AGG(msd.id, ',') AS detail_id
      FROM ms_suitable_detail msd
      GROUP BY msd.main_id
    ) AS details 
      ON msm.id = details.main_id 
    WHERE 1=1
      --roofMtCd AND msm.roof_mt_cd = ':roofMtCd'
      --productName AND msm.product_name LIKE '%:productName%'
    ;
    `

    // 검색 조건 설정
    if (category) {
      query = query.replace('--roofMtCd ', '')
      query = query.replace(':roofMtCd', category)
    }
    if (keyword) {
      query = query.replace('--productName ', '')
      query = query.replace(':productName', keyword)
    }

    const suitableIdSet = await prisma.$queryRawUnsafe(query)

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