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

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

    // @ts-ignore
    const headCd = await prisma.BC_COMM_H.findFirst({
      where: {
        HEAD_ID: headCode,
      },
      select: {
        HEAD_CD: true,
      },
    })

    if (!headCd) {
      return NextResponse.json({ error: `${headCode}를 찾을 수 없습니다` }, { status: 404 })
    }

    // @ts-ignore
    const roofMaterials: CommCode[] = await prisma.BC_COMM_L.findMany({
      where: {
        HEAD_CD: headCd.HEAD_CD,
      },
      select: {
        HEAD_CD: true,
        CODE: true,
        CODE_JP: true,
      },
      orderBy: {
        CODE: 'asc',
      },
    })

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