import type { SessionData } from '@/types/Auth'
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 { tracking } from '@/libs/tracking'

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.data)

  let finalResult = {}

  if (result.data.result.resultCode === 'S') {
    tracking({
      url: `/api/auth/login`,
      data: JSON.stringify({
        loginId,
        pwd,
      }),
    })
    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 {
      session.role = 'User'
    }

    console.log('end session edit!')

    await session.save()

    const resultForSession = {
      LANG_CD: result.data.data.langCd,
      CURR_PAGE: result.data.data.currPage,
      ROW_COUNT: result.data.data.rowCount,
      START_ROW: result.data.data.startRow,
      END_ROW: result.data.data.endRow,
      COMP_CD: result.data.data.compCd,
      AGENCY_STORE_ID: result.data.data.agencyStoreId,
      STORE_ID: result.data.data.storeId,
      STORE_NM: result.data.data.storeNm,
      USER_ID: result.data.data.userId,
      CATEGORY: result.data.data.category,
      USER_NM: result.data.data.userNm,
      USER_NM_KANA: result.data.data.userNmKana,
      TEL_NO: result.data.data.telNo,
      FAX: result.data.data.fax,
      EMAIL: result.data.data.email,
      LAST_EDIT_USER: result.data.data.lastEditUser,
      STORE_GUBUN: result.data.data.storeGubun,
      PW_CURR: result.data.data.pwCurr,
      PWD_INIT_YN: result.data.data.pwdInitYn,
      APPR_STAT_CD: result.data.data.apprStatCd,
      LOGIN_FAIL_CNT: result.data.data.loginFailCnt,
      LOGIN_FAIL_MIN_YN: result.data.data.loginFailMinYn,
      PRICE_VIEW_STAT_CD: result.data.data.priceViewStatCd,
      GROUP_ID: result.data.data.groupId,
      STORE_LVL: result.data.data.storeLvl,
      CUST_CD: result.data.data.custCd,
      BUILDER_NO: result.data.data.builderNo,
      IS_LOGGED_IN: true,
      ROLE: '',
    }

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

    finalResult = {
      code: 200,
      message: 'Login is Succecss!!',
      result: resultForSession,
    }
  } else {
    finalResult = {
      code: 400,
      message: 'Login is Failed!!',
      result: {},
    }
  }

  return NextResponse.json(finalResult)
}
