import type { SessionData } from '@/types/Auth'
import { NextResponse } from 'next/server'
import { cookies } from 'next/headers'
import { getIronSession } from 'iron-session'
import executeQuery from '@/libs/partner'
import { sessionOptions } from '@/libs/session'

export async function POST(request: Request) {
  const cookieStore = await cookies()
  const session = await getIronSession<SessionData>(cookieStore, sessionOptions)
  const { loginId, pwd } = await request.json()

  const sql = `
  SELECT
    r.data_id,
    u.id AS user_id,
    u.login_id AS user_login_id,
    u.password AS user_password,
    u.user_name AS user_name,
    u.user_name_kana AS user_name_kana,
    u.sei AS user_sei,
    u.mei AS user_mei,
    u.sei_kana AS user_sei_kana,
    u.mei_kana AS user_mei_kana,
    u.user_tel AS user_tel,
    u.user_fax AS user_fax,
    u.status AS user_status,
    u.seko_id AS user_seko_id,
    u.seko_limit AS user_seko_limit,
    s.id AS supplier_id,
    s.code AS supplier_code,
    s.name AS supplier_name,
    s.name_kana AS supplier_name_kana,
    s.kind AS supplier_kind
  FROM
      R_DATA r
  JOIN
      M_USER u ON r.data_id = u.id
  JOIN
      M_SUPPLIER s ON r.relation_id = s.id
  WHERE
    u.status = '1'
    AND
    u.seko_id is not null
    AND
    u.seko_limit > now()
    AND
    s.kind = '4'
    AND
    u.login_id = ?
    AND
    u.password = ?
  `
  // const sql = 'SELECT * FROM M_USER'
  const data = (await executeQuery(sql, [loginId, pwd])) as any[]
  console.log('🚀 ~ POST ~ data:', data)

  if (data.length > 0) {
    console.log('start session edit!')
    session.langCd = null
    session.currPage = null
    session.rowCount = null
    session.startRow = null
    session.endRow = null
    session.compCd = null
    session.agencyStoreId = null
    session.storeId = data[0].supplier_code
    session.storeNm = data[0].supplier_name
    session.userId = data[0].user_login_id
    session.category = data[0].supplier_name
    session.userNm = `${data[0].user_sei} ${data[0].user_mei}`
    session.userNmKana = `${data[0].user_sei_kana} ${data[0].user_mei_kana}`
    session.telNo = data[0].tel
    session.fax = data[0].fax
    session.email = data[0].user_login_id
    session.lastEditUser = null
    session.storeGubun = null
    session.pwCurr = null
    session.pwdInitYn = null
    session.apprStatCd = null
    session.loginFailCnt = null
    session.loginFailMinYn = null
    session.priceViewStatCd = null
    session.groupId = null
    session.storeLvl = null
    session.custCd = null
    session.builderNo = data[0].user_seko_id
    session.isLoggedIn = true
    session.role = 'Partner'

    console.log('end session edit!')

    await session.save()
  }

  // qsp 유저 데이터 모양과 맞춰서 변환
  const result = {
    LANG_CD: null,
    CURR_PAGE: null,
    ROW_COUNT: null,
    START_ROW: null,
    END_ROW: null,
    COMP_CD: null,
    AGENCY_STORE_ID: null,
    STORE_ID: data[0].supplier_code,
    STORE_NM: data[0].supplier_name,
    USER_ID: data[0].user_login_id,
    CATEGORY: data[0].supplier_name,
    USER_NM: `${data[0].user_sei} ${data[0].user_mei}`,
    USER_NM_KANA: `${data[0].user_sei_kana} ${data[0].user_mei_kana}`,
    TEL_NO: data[0].tel,
    FAX: data[0].fax,
    EMAIL: data[0].user_login_id,
    LAST_EDIT_USER: null,
    STORE_GUBUN: null,
    PW_CURR: null,
    PWD_INIT_YN: null,
    APPR_STAT_CD: null,
    LOGIN_FAIL_CNT: null,
    LOGIN_FAIL_MIN_YN: null,
    PRICE_VIEW_STAT_CD: null,
    GROUP_ID: null,
    STORE_LVL: null,
    CUST_CD: null,
    BUILDER_NO: data[0].user_seko_id,
    IS_LOGGED_IN: true,
    ROLE: 'Partner',
  }

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