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 pageNumber = parseInt(searchParams.get('pageNumber') || '0')
    const itemPerPage = parseInt(searchParams.get('itemPerPage') || '0')
    if (pageNumber === 0 || itemPerPage === 0) {
      return NextResponse.json({ error: '페이지 번호와 페이지당 아이템 수가 필요합니다' }, { status: 400 })
    }

    const category = searchParams.get('category')
    const keyword = searchParams.get('keyword')

    let query = `
    SELECT 
      msm.id
      , msm.product_name
      , details.detail_cnt
      , details.detail
    FROM ms_suitable_main msm
    LEFT JOIN (
      SELECT
        msd.main_id
        , COUNT(msd.id) AS detail_cnt
        , (
          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 
    WHERE 1=1
      --roofMtCd AND msm.roof_mt_cd = ':roofMtCd'
      --productName AND msm.product_name LIKE '%:productName%'
    ORDER BY msm.product_name
    OFFSET (@P1 - 1) * @P2 ROWS
    FETCH NEXT @P2 ROWS ONLY;
    `

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

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

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