import { date } from 'alga-js'
import fetchHelper from './fetchHelper'
import sqliteHelper from './sqliteHelper'

export default async function refreshTokenHelper(event: any) {
  const config = useRuntimeConfig()
  let data: any = {}
  const logshipSession = getCookie(event, 'logship_session')

  //@ts-ignore
  const userName = getCookie(event, 'logship_xu') //await useStorage().getItem('logship_username_'+logshipSession)
  //@ts-ignore
  const password = getCookie(event, 'logship_py') //await useStorage().getItem('logship_password_'+logshipSession)
  //@ts-ignore
  let token = getCookie(event, 'logship_it') //await useStorage().getItem('logship_token_'+logshipSession)
  let refreshToken = getCookie(event, 'logship_rt')
  const clientId = getCookie(event, 'logship_client_id')
  const roleId = getCookie(event, 'logship_role_id')
  const organizationId = getCookie(event, 'logship_organization_id')
  const warehouseId = getCookie(event, 'logship_warehouse_id')
  const language = getCookie(event, 'logship_language')
  const userId = getCookie(event, 'logship_user_id')
  let resToken: any = {}

  try {
    resToken = await fetchHelper(event, 'auth/refresh', 'POST', token, {
      refresh_token: refreshToken,
      clientId: clientId,
      userId: userId
    })
  } catch(error: any) {
    resToken = await fetchHelper(event, 'auth/tokens', 'POST', '', {
      userName: Buffer.from(userName, 'base64'),
      password: Buffer.from(password, 'base64'),
      parameters: {
        clientId: clientId,
        roleId: roleId,
        organizationId: organizationId ?? '',
        warehouseId: warehouseId ?? '',
        language: language ?? 'en_US'
      }
    })
  }
  
  if(resToken.userId) {
    setCookie(event, 'logship_user_id', resToken.userId)

    const resUser: any = await fetchHelper(event, 'models/ad_user/'+resToken.userId, 'GET', resToken.token, {
      headers: {
        'Authorization': 'Bearer '+resToken.token
      }
    })
    if(resUser) {
      setCookie(event, 'logship_user', resUser)
    }
    if(clientId) {
      const resClient: any = await fetchHelper(event, 'models/ad_client/'+clientId, 'GET', resToken.token, null)
      if(resClient) {
        setCookie(event, 'logship_client', resClient)
        data['client'] = resClient
      }
    }
    if(roleId) {
      const resRole: any = await fetchHelper(event, 'models/ad_role/'+roleId, 'GET', resToken.token, null)
      if(resRole) {
        setCookie(event, 'logship_role', resRole)
        data['role'] = resRole
      }
    }
    if(organizationId) {
      const resOrg: any = await fetchHelper(event, 'models/ad_org/'+organizationId, 'GET', resToken.token, null)
      if(resOrg) {
        setCookie(event, 'logship_organization', resOrg)
        data['organization'] = resOrg
      }
    }
    if(warehouseId) {
      const resWarehouse: any = await fetchHelper(event, 'models/m_warehouse/'+warehouseId, 'GET', resToken.token, null)
      if(resWarehouse) {
        setCookie(event, 'logship_warehouse', resWarehouse)
        data['warehouse'] = resWarehouse
      }
    }

  }
  /*if(resToken.language) {
    setCookie(event, 'language', resToken.language)
  }*/
  if(resToken.token) {
    //await useStorage().setItem('logship_token_'+logshipSession, resToken.token)
    token = resToken.token
    setCookie(event, 'logship_it', resToken.token)
    setCookie(event, 'logship_rt', resToken.refresh_token)

    sqliteHelper(event, (db) => {
      const stmt = db.prepare("INSERT INTO refresh_tokens (refresh_token, token, expiration) VALUES (?, ?, ?)")
      stmt.run(resToken.refresh_token, resToken.token, date.add(date.now(''), 1))
      stmt.finalize()
    })

    return resToken.token
  }

  return token
}