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

export default defineEventHandler(async (event) => {
  const config = useRuntimeConfig()
  const body = await readBody(event)
  let data: any = {}
  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')

  try {
    let newParameters: any = {}

    if(!body.selectRole && clientId && roleId) {
      newParameters = {
        parameters: {
          clientId,
          roleId
        }
      }

      if(organizationId) {
        //@ts-ignore
        newParameters['parameters']['organizationId'] = organizationId
      }
      if(warehouseId) {
        //@ts-ignore
        newParameters['parameters']['warehouseId'] = warehouseId
      }
      if(language) {
        //@ts-ignore
        newParameters['parameters']['language'] = language
      }
    }

    const resToken: any = await fetchHelper(event, 'auth/tokens', 'POST', '', {
      userName: body.userName,
      password: body.password,
      ...newParameters
    })
    if(resToken.token) {
      const logshipSession = string.uniqid()
      
      data['token'] = resToken.token
      data['session'] = logshipSession

      setCookie(event, 'logship_session', logshipSession)
      setCookie(event, 'logship_xu', Buffer.from(body.userName, 'binary').toString('base64'))
      setCookie(event, 'logship_py', Buffer.from(body.password, 'binary').toString('base64'))
      setCookie(event, 'logship_it', resToken.token)
      
      //await useStorage().setItem('logship_username_'+logshipSession, body.userName)
      //await useStorage().setItem('logship_password_'+logshipSession, body.password)
      //await useStorage().setItem('logship_token_'+logshipSession, resToken.token)
    }
    if(resToken?.clients) {
      setCookie(event, 'logship_clients', resToken.clients)
      data['clients'] = resToken.clients
      /*if(resToken?.token && (resToken.clients?.length ?? 0) === 1) {
        const clientId = resToken.clients[0].id
        const resClient: any = await fetchHelper(event, 'models/ad_client/'+clientId, 'GET', resToken.token, null)
        if(resClient) {
          setCookie(event, 'logship_client', resClient)
          data['client'] = resClient
        }
        const resRoles: any = await fetchHelper(event, 'models/ad_role', 'GET', resToken.token, null)
        if((resRoles?.length ?? 0) === 1) {
          const resRole: any = await fetchHelper(event, 'models/ad_role/'+resRoles[0].id+'?includeAttributes=true', 'GET', resToken.token, null)
          if(resRole) {
            // Save complete role data in cookie
            setCookie(event, 'logship_role', resRole)
            data['role'] = resRole
          }
        }
        const resOrgs: any = await fetchHelper(event, 'models/ad_org', 'GET', resToken.token, null)
        if((resOrgs?.length ?? 0) === 1) {
          const resOrg: any = await fetchHelper(event, 'models/ad_org/'+resOrgs[0].id, 'GET', resToken.token, null)
          if(resOrg) {
            setCookie(event, 'logship_organization', resOrg)
            data['organization'] = resOrg
          }
        }
        const resWarehouses: any = await fetchHelper(event, 'models/m_warehouse', 'GET', resToken.token, null)
        if(resWarehouses) {
          const resWarehouse: any = await fetchHelper(event, 'models/m_warehouse/'+resWarehouses[0].id, 'GET', resToken.token, null)
          if(resWarehouse) {
            setCookie(event, 'logship_warehouse', resWarehouse)
            data['warehouse'] = resWarehouse
          }
        }
        setCookie(event, 'logship_language', 'en_US')
        data['language'] = 'en_US'
        const resToken2: any = await fetchHelper(event, 'auth/tokens', 'PUT', resToken.token, {
          clientId: data['client'],
          roleId: data['role'],
          organizationId: data['organization'],
          warehouseId: data['warehouse'],
          language: data['language']
        })
        if(resToken2.token) {
          setCookie(event, 'logship_it', resToken2.token) //await useStorage().setItem('logship_token_'+logshipSession, resToken.token)
          setCookie(event, 'logship_rt', resToken2.refresh_token)
          data['token'] = resToken2.token
          data['refresh_token'] = resToken2.refresh_token
        }
      }*/
    } else {
      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(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) {
          // 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/'+roleId+'?includeAttributes=true', 'GET', resToken.token, null)

          if(resRole) {
            // Log to verify we have all needed data
            console.log('Role data fetched during login:', {
              roleId: 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(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
          }
        }
        data['toDashboard'] = true
      }
      if(resToken.language) {
        setCookie(event, 'logship_language', resToken.language)
        data['language'] = resToken.language
      }
    }
    if(resToken.refresh_token) {
      //@ts-ignore
      setCookie(event, 'logship_rt', resToken.refresh_token)

      sqliteHelper(event, (db: any) => {
        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()
      })
    }
  } catch(error: any) {
    // Handle authentication errors with user-friendly messages
    if (error.status === 401) {
      data = {
        body: {
          userName: body.userName,
          password: body.password
        }, 
        status: error.status,
        message: 'Wrong username or password entered. Please check your credentials and try again.'
      }
    } else if (error.status === 403) {
      data = {
        body: {
          userName: body.userName,
          password: body.password
        }, 
        status: error.status,
        message: 'Access denied. Please contact your administrator.'
      }
    } else if (error.status >= 500) {
      data = {
        body: {
          userName: body.userName,
          password: body.password
        }, 
        status: error.status,
        message: 'Server error. Please try again later or contact support.'
      }
    } else {
      // For other errors, provide a generic friendly message
      data = {
        body: {
          userName: body.userName,
          password: body.password
        }, 
        status: error.status,
        message: error.message || 'Login failed. Please try again.'
      }
    }
  }

  return data
})