import { string } from 'alga-js'
import refreshTokenHelper from "../../../utils/refreshTokenHelper"
import forceLogoutHelper from "../../../utils/forceLogoutHelper"
import errorHandlingHelper from "../../../utils/errorHandlingHelper"

/**
 * GET /api/admin/users/search?q=&organizationId=&type=all|lead|external|internal&limit=
 * Live-search box for ad_user (e.g. the dashboard quick-contact modal, so an
 * existing contact/lead can be reused instead of creating a duplicate).
 * `type` mirrors the site's existing Users/Leads/External Users split
 * (server/api/admin/users/{index,leads,external-users,internal-users}.get.ts):
 *   lead     = isSalesLead OR isVendorLead
 *   external = isSystemUser eq false AND not a lead
 *   internal = isSystemUser eq true AND not a lead
 *   all      = active users, no lead/system split
 * `organizationId` defaults to the caller's own org (cookie); pass `all` to
 * search across every organization.
 */
const handleFunc = async (event: any, authToken: any = null) => {
  const data: any = { records: [] }
  const token = authToken ?? await getTokenHelper(event)
  const query = getQuery(event)
  const q = String(query.q || query.search || '').trim()
  const limit = Math.min(30, Math.max(1, parseInt(query.limit as string) || 15))
  const type = ['lead', 'external', 'internal'].includes(String(query.type)) ? String(query.type) : 'all'

  const clauses = ['isActive eq true']
  if (type === 'lead') clauses.push('(isSalesLead eq true OR isVendorLead eq true)')
  else if (type === 'external') clauses.push('isSystemUser eq false AND isSalesLead eq false AND isVendorLead eq false')
  else if (type === 'internal') clauses.push('isSystemUser eq true AND isSalesLead eq false AND isVendorLead eq false')

  const orgParam = String(query.organizationId ?? '')
  const organizationId = orgParam === 'all' ? '' : (orgParam || getCookie(event, 'logship_organization_id') || '')
  if (organizationId) clauses.push(`AD_Org_ID eq ${organizationId}`)

  if (q) {
    const esc = q.replace(/'/g, "''").toLowerCase()
    clauses.push(`(contains(tolower(Name),'${esc}') OR contains(tolower(EMail),'${esc}') OR contains(tolower(Phone),'${esc}'))`)
  }

  const res: any = await event.context.fetch(
    `models/ad_user?$filter=${string.urlEncode(clauses.join(' AND '))}&$orderby=${string.urlEncode('Name asc')}&$top=${limit}`,
    'GET', token, null
  )

  if (res?.records) {
    data.records = res.records.map((r: any) => ({
      id: r.id ?? r.AD_User_ID,
      name: r.Name || '',
      email: r.EMail || '',
      phone: r.Phone || '',
      isLead: (r.isSalesLead ?? r.IsSalesLead) === true || (r.isVendorLead ?? r.IsVendorLead) === true,
      isSystemUser: (r.isSystemUser ?? r.IsSystemUser) === true,
      orgId: r.AD_Org_ID?.id ?? null,
      orgName: r.AD_Org_ID?.identifier || ''
    }))
  }

  return data
}

export default defineEventHandler(async (event) => {
  let data: any = {}

  try {
    data = await handleFunc(event)
  } catch (err: any) {
    try {
      const authToken: any = await refreshTokenHelper(event)
      data = await handleFunc(event, authToken)
    } catch (error: any) {
      data = errorHandlingHelper(err?.data ?? err, error?.data ?? error)
      forceLogoutHelper(event, data)
    }
  }

  return data
})
