import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/libs/prisma'
import { convertToSnakeCase } from '@/utils/common-utils'

export async function GET(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  try {
    const { id } = await params
    // @ts-ignore
    const survey = await prisma.SD_SURVEY_SALES_BASIC_INFO.findUnique({
      where: { ID: Number(id) },
      include: {
        DETAIL_INFO: true,
      },
    })
    return NextResponse.json(survey)
  } catch (error) {
    console.error('Error fetching survey:', error)
    return NextResponse.json({ error: 'Failed to fetch survey' }, { status: 500 })
  }
}

const getNewSrlNo = async (srlNo: string, storeId: string) => {
  let newSrlNo = srlNo
  console.log('srlNo:: ', srlNo)
  if (srlNo.startsWith('一時保存')) {
    //@ts-ignore
    const lastSurvey = await prisma.SD_SURVEY_SALES_BASIC_INFO.findFirst({
      where: {
        SRL_NO: {
          startsWith: storeId,
        },
      },
      orderBy: {
        ID: 'desc',
      },
    })
    const lastNo = lastSurvey ? parseInt(lastSurvey.SRL_NO.slice(-3)) : 0
    newSrlNo =
      storeId +
      new Date().getFullYear().toString().slice(-2) +
      (new Date().getMonth() + 1).toString().padStart(2, '0') +
      new Date().getDate().toString().padStart(2, '0') +
      (lastNo + 1).toString().padStart(3, '0')
  }
  return newSrlNo
}

export async function PUT(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  try {
    const { id } = await params
    const body = await request.json()
    const { detailInfo, ...basicInfo } = body.survey

    // PUT 요청 시 임시저장 여부 확인 후 임시저장 시 기존 SRL_NO 사용, 기본 저장 시 새로운 SRL_NO 생성
    const newSrlNo = body.isTemporary ? body.survey.srlNo : await getNewSrlNo(body.survey.srlNo, body.storeId)
    // @ts-ignore
    const survey = await prisma.SD_SURVEY_SALES_BASIC_INFO.update({
      where: { ID: Number(id) },
      data: {
        ...convertToSnakeCase(basicInfo),
        SRL_NO: newSrlNo,
        UPT_DT: new Date(),
        DETAIL_INFO: {
          update: convertToSnakeCase(detailInfo),
        },
      },
      include: {
        DETAIL_INFO: true,
      },
    })
    return NextResponse.json(survey)
  } catch (error) {
    console.error('Error updating survey:', error)
    return NextResponse.json({ error: 'Failed to update survey' }, { status: 500 })
  }
}

export async function DELETE(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  try {
    const { id } = await params

    await prisma.$transaction(async (tx) => {
      // @ts-ignore
      const detailData = await tx.SD_SURVEY_SALES_BASIC_INFO.findUnique({
        where: { ID: Number(id) },
        select: {
          DETAIL_INFO: true,
        },
      })

      if (detailData?.DETAIL_INFO?.ID) {
        // @ts-ignore
        await tx.SD_SURVEY_SALES_DETAIL_INFO.delete({
          where: { ID: Number(detailData.DETAIL_INFO.ID) },
        })
      }

      // @ts-ignore
      await tx.SD_SURVEY_SALES_BASIC_INFO.delete({
        where: { ID: Number(id) },
      })
    })

    return NextResponse.json({ message: 'Survey deleted successfully' })
  } catch (error) {
    console.error('Error deleting survey:', error)
    return NextResponse.json({ error: 'Failed to delete survey' }, { status: 500 })
  }
}

export async function PATCH(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  try {
    const { id } = await params
    const body = await request.json()

    // 제출 시 기존 SRL_NO 확인 후 '임시저장'으로 시작하면 새로운 SRL_NO 생성
    const newSrlNo = await getNewSrlNo(body.srlNo, body.storeId)

    if (body.targetId) {
      // @ts-ignore
      const survey = await prisma.SD_SURVEY_SALES_BASIC_INFO.update({
        where: { ID: Number(id) },
        data: {
          SUBMISSION_STATUS: true,
          SUBMISSION_DATE: new Date(),
          SUBMISSION_TARGET_ID: body.targetId,
          UPT_DT: new Date(),
          SRL_NO: newSrlNo,
        },
      })
      console.log(survey)
      return NextResponse.json({ message: 'Survey confirmed successfully' })
    }
  } catch (error) {
    console.error('Error updating survey:', error)
    return NextResponse.json({ error: 'Failed to update survey' }, { status: 500 })
  }
}
