import { cookies } from 'next/headers'
import { NextResponse } from 'next/server'

import { getIronSession } from 'iron-session'
import { axiosInstance } from '@/libs/axios'
import { sessionOptions } from '@/libs/session'

import type { SessionData } from '@/types/Auth'

export async function POST(request: Request) {
  const { loginId, pwd } = await request.json()

  const result = await axiosInstance(`${process.env.NEXT_PUBLIC_QSP_API_URL}`).post(`/api/user/login`, {
    loginId,
    pwd,
  })
  // console.log('🚀 ~ result ~ result:', result)

  if (result.data.result.code === 200) {
    const cookieStore = await cookies()
    const session = await getIronSession<SessionData>(cookieStore, sessionOptions)

    console.log('start session edit!')
    session.langCd = result.data.data.langCd
    session.currPage = result.data.data.currPage
    session.rowCount = result.data.data.rowCount
    session.startRow = result.data.data.startRow
    session.endRow = result.data.data.endRow
    session.compCd = result.data.data.compCd
    session.agencyStoreId = result.data.data.agencyStoreId
    session.storeId = result.data.data.storeId
    session.storeNm = result.data.data.storeNm
    session.userId = result.data.data.userId
    session.category = result.data.data.category
    session.userNm = result.data.data.userNm
    session.userNmKana = result.data.data.userNmKana
    session.telNo = result.data.data.telNo
    session.fax = result.data.data.fax
    session.email = result.data.data.email
    session.lastEditUser = result.data.data.lastEditUser
    session.storeGubun = result.data.data.storeGubun
    session.pwCurr = result.data.data.pwCurr
    session.pwdInitYn = result.data.data.pwdInitYn
    session.apprStatCd = result.data.data.apprStatCd
    session.loginFailCnt = result.data.data.loginFailCnt
    session.loginFailMinYn = result.data.data.loginFailMinYn
    session.priceViewStatCd = result.data.data.priceViewStatCd
    session.groupId = result.data.data.groupId
    session.storeLvl = result.data.data.storeLvl
    session.custCd = result.data.data.custCd
    session.builderNo = result.data.data.builderNo
    session.isLoggedIn = true

    if (result.data.data.userId === 'T01') {
      session.role = 'T01'
    } else if (result.data.data.groupId === '60000') {
      session.role = 'Admin'
    } else if (result.data.data.groupId === '70000' && result.data.data.builderNo === null) {
      session.role = 'Admin_Sub'
    } else if (result.data.data.groupId === '70000' && result.data.data.builderNo !== null) {
      session.role = 'Builder'
    } else if (result.data.data.groupId === '90000' && result.data.data.builderNo !== null) {
      session.role = 'Partner'
    } else {
      session.role = 'User'
    }

    console.log('end session edit!')

    await session.save()
  }

  return NextResponse.json({ code: 200, message: 'Login is Succecss!!', result: result.data.data })
}
