import { NextRequest, NextResponse } from 'next/server'
import { loggerWrapper } from '@/libs/api-wrapper'
import { prisma } from '@/libs/prisma'
import { CommonCode } from '@/types/Inquiry'

async function getCommCode(request: NextRequest): Promise<NextResponse> {
  try {
    const searchParams = request.nextUrl.searchParams
    const headId = searchParams.get('headId')

    if (!headId) return NextResponse.json({ error: '필수 파라미터가 없습니다' }, { status: 400 })

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

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

    // @ts-ignore
    const results: CommCode[] = await prisma.BC_COMM_L.findMany({
      where: {
        HEAD_CD: commHeadData.HEAD_CD,
      },
      select: {
        HEAD_CD: true,
        CODE: true,
        CODE_JP: true,
        REF_CHR1: true,
      },
      orderBy: {
        CODE: 'asc',
      },
    })
    return NextResponse.json(results)
  } catch (error) {
    console.error('❌ 데이터 조회 중 오류가 발생했습니다:', error)
    return NextResponse.json({ error: '데이터 조회 중 오류가 발생했습니다' }, { status: 500 })
  }
}

const getSaleOffice = async (headCode: string) => {
  // @ts-ignore
  const commCodeSaleOffice: CommCode[] = await prisma.BC_COMM_L.findMany({
    where: {
      HEAD_CD: headCode,
      REF_NUM1: 1,
    },
    select: {
      CODE: true,
      CODE_JP: true,
      REF_CHR1: true,
      REF_NUM1: true,
    },
  })
  return NextResponse.json(commCodeSaleOffice)
}

/**
 * @description QNA 공통 코드 조회
 * @returns {CommonCode[]} QNA 공통 코드 목록
 */
const getQnaCd = async () => {
  // @ts-ignore
  const headCdList: { HEAD_CD: string; HEAD_ID: string }[] = await prisma.BC_COMM_H.findMany({
    where: {
      OR: [{ HEAD_ID: { in: ['QNA_CLS_LRG_CD'] } }, { HEAD_ID: { in: ['QNA_CLS_MID_CD'] } }, { HEAD_ID: { in: ['QNA_CLS_SML_CD'] } }],
    },
    select: {
      HEAD_CD: true,
      HEAD_ID: true,
    },
  })
  const result: CommonCode[] = []
  // @ts-ignore
  const commCodeQna: CommCode[] = await prisma.BC_COMM_L.findMany({
    where: {
      HEAD_CD: {
        in: headCdList.map((item) => item.HEAD_CD).filter(Boolean),
      },
    },
    select: {
      HEAD_CD: true,
      CODE: true,
      CODE_JP: true,
      REF_CHR1: true,
    },
  })
  commCodeQna.forEach((item) => {
    result.push({
      // @ts-ignore
      headCd: item.HEAD_CD,
      // @ts-ignore
      headId: headCdList.find((headCd) => headCd.HEAD_CD === item.HEAD_CD)?.HEAD_ID ?? '',
      // @ts-ignore
      code: item.CODE,
      // @ts-ignore
      name: item.CODE_JP,
      // @ts-ignore
      refChar1: item.REF_CHR1 ?? '',
    })
  })
  return NextResponse.json(result)
}
export const GET = loggerWrapper(getCommCode)
