import refreshTokenHelper from "../../utils/refreshTokenHelper"
import forceLogoutHelper from "../../utils/forceLogoutHelper"
import errorHandlingHelper from "../../utils/errorHandlingHelper"
import fetchHelper from '../../utils/fetchHelper'

const selectRole = async (event: any, body: any, config: any) => {
  let data: any = {}
  const logshipSession = getCookie(event, 'logship_session')

  //@ts-ignore
  let token: string = getCookie(event, 'logship_it') //await useStorage().getItem('logship_token_'+logshipSession)

  const resToken: any = await fetchHelper(event, 'auth/tokens', 'PUT', token, {
    clientId: body.clientId,
    roleId: body.roleId,
    organizationId: body.organizationId,
    warehouseId: body.warehouseId,
    language: body.language
  })
  if(resToken.token) {
    setCookie(event, 'logship_it', resToken.token) //await useStorage().setItem('logship_token_'+logshipSession, resToken.token)
    setCookie(event, 'logship_rt', resToken.refresh_token)
    data['token'] = resToken.token
    data['refresh_token'] = resToken.refresh_token
  }
  if(resToken.userId) {
    setCookie(event, 'logship_user_id', resToken.userId)
    data['userId'] = resToken.userId

    const resUser: any = await fetchHelper(event, 'models/ad_user/'+resToken.userId, 'GET', resToken.token, null)
    if(resUser) {
      setCookie(event, 'logship_user', resUser)
      data['user'] = resUser
    }
    if(body.clientId) {
      const resClient: any = await fetchHelper(event, 'models/ad_client/'+body.clientId, 'GET', resToken.token, null)
      if(resClient) {
        setCookie(event, 'logship_client', resClient)
        data['client'] = resClient
      }
    }
    if(body.roleId) {
      // Use a more specific endpoint or parameters to ensure we get all role data including AD_Tree_Menu_ID
      const resRole: any = await fetchHelper(event, 'models/ad_role/'+body.roleId+'?includeAttributes=true', 'GET', resToken.token, null)

      if(resRole) {
        // Log to verify we have all needed data
        console.log('Role data fetched during role selection:', {
          roleId: body.roleId,
          hasTreeMenuId: !!resRole.AD_Tree_Menu_ID,
          treeMenuIdType: typeof resRole.AD_Tree_Menu_ID
        })

        // Save complete role data in cookie
        setCookie(event, 'logship_role', resRole)
        data['role'] = resRole
      }
    }
    if(body.organizationId) {
      const resOrg: any = await fetchHelper(event, 'models/ad_org/'+body.organizationId, 'GET', resToken.token, null)
      if(resOrg) {
        setCookie(event, 'logship_organization', resOrg)
        data['organization'] = resOrg
      }
    }
    if(body.warehouseId) {
      const resWarehouse: any = await fetchHelper(event, 'models/m_warehouse/'+body.warehouseId, 'GET', resToken.token, null)
      if(resWarehouse) {
        setCookie(event, 'logship_warehouse', resWarehouse)
        data['warehouse'] = resWarehouse
      }
    }

  }
  if(resToken.language) {
    setCookie(event, 'logship_language', resToken.language)
    data['language'] = resToken.language
  }

  setCookie(event, 'logship_client_id', body.clientId)
  setCookie(event, 'logship_role_id', body.roleId)
  setCookie(event, 'logship_organization_id', body.organizationId)
  setCookie(event, 'logship_warehouse_id', body.warehouseId)

  return data
}

export default defineEventHandler(async (event) => {
  const config = useRuntimeConfig()
  const body = await readBody(event)

  let data: any = {}

  try {
    data = selectRole(event, body, config)
  } catch(err: any) {
    try {
      refreshTokenHelper(event)
      data = selectRole(event, body, config)
    } catch(error) {
      data = {
        body: {
          clientId: body.clientId,
          roleId: body.roleId,
          organizationId: body.organizationId,
          warehouseId: body.warehouseId,
          language: body.language
        }, 
        //@ts-ignore
        status: error.status,
        //@ts-ignore
        message: error.message
      }
    }
  }

  return data
})