import { string } from 'alga-js'
import elasticHelper from "../../../utils/elasticHelper"
import elasticsearchHelper from "../../../utils/elasticsearchHelper"
import errorHandlingHelper from "../../../utils/errorHandlingHelper"


export default defineEventHandler(async (event) => {
  const qry = getRouterParam(event, 'query')
  const query = getQuery(event)
  
  // Get the defaultSideBarMenu variable from query parameters
  const defaultSideBarMenu = query.defaultSideBarMenu || 'Menu'

  // Log auth context details - for debugging purposes only
  // const userOrgId = event.context.auth?.organizationId || "No org ID found"
  // const userRoleId = event.context.auth?.roleId || "No role ID found"
  // const userClientId = event.context.auth?.clientId || "No client ID found"
  // console.log('Search API - Auth context info:', {
  //   query: qry,
  //   orgId: userOrgId,
  //   roleId: userRoleId,
  //   clientId: userClientId,
  //   defaultSideBarMenu: defaultSideBarMenu
  // })

  // Get ad_org_id from role session data
  const adOrgId = event.context.auth?.organizationId || "0"

  // You can also log it for debugging
  // console.log('ad_org_id from role session:', adOrgId)
  // console.log('defaultSideBarMenu:', defaultSideBarMenu)

  let data: any = {
    c_bpartner: [],
    m_product: [],
    c_order: [],
    m_inout: [],
    ad_user: [],
    c_invoice: [],
    r_request: []
  }

  try {
    const models: string[] = Object.keys(data)
    for(let model of models) {
      try {
        // Special handling for m_product to group by product_name
        if (model === 'm_product') {
          // Get the organization ID from auth context
          const userOrgId = event.context.auth?.organizationId || "11"
          // console.log(`m_product search: Filtering by organization ID: ${userOrgId}`)

          // Build must array conditionally
          const mustConditions: any[] = [
            {
              query_string: {
                query: qry
              }
            }
          ]

          // Only add ad_org_id filter if defaultSideBarMenu is not 'c'
          if (defaultSideBarMenu === 'c') {
            mustConditions.push({
              term: {
                "ad_org_id": userOrgId
              }
            })
          }

          // Use POST with aggregation for m_product with conditional organization filter
          const queryBody = {
            size: 0, // We don't need regular hits when using aggregations
            query: {
              bool: {
                must: mustConditions
              }
            },
            aggs: {
              group_by_product_name: {
                terms: {
                  field: "product_name.keyword",
                  size: 100 // Limit to 100 unique product names
                },
                aggs: {
                  top_product_hits: {
                    top_hits: {
                      size: 1 // Get only the top document for each product name
                    }
                  }
                }
              }
            }
          }

          const res: any = await elasticHelper(`${model}/_search?pretty`, 'POST', queryBody)

          if(res && res.aggregations?.group_by_product_name?.buckets) {
            // Transform aggregation results to match the expected format
            const hits = res.aggregations.group_by_product_name.buckets.map((bucket: any) =>
              bucket.top_product_hits.hits.hits[0]
            )

            // Create a structure that matches what the frontend expects
            data[model] = {
              hits: {
                hits: hits
              }
            }
          } else {
            data[model] = {
              hits: {
                hits: []
              }
            }
          }
        } else {
          // Get the organization ID from auth context
          const userOrgId = event.context.auth?.organizationId || "11"

          // console.log(`${model} search: Filtering by organization ID: ${userOrgId}`)

          // Build must array conditionally
          const mustConditions: any[] = [
            {
              query_string: {
                query: qry
              }
            }
          ]

          // Only add ad_org_id filter if defaultSideBarMenu is not 'c'
          if (defaultSideBarMenu === 'c') {
            mustConditions.push({
              term: {
                "ad_org_id": userOrgId
              }
            })
          }

          // Create a query with conditional organization filter
          const queryBody = {
            query: {
              bool: {
                must: mustConditions
              }
            }
          }

          console.log(queryBody)
          // Use POST with the query body to apply the conditional organization filter
          const res: any = await elasticHelper(`${model}/_search?pretty`, 'POST', queryBody)
          if(res) {
            data[model] = res
          } else {
            data[model] = {
              hits: {
                hits: []
              }
            }
          }
        }
      } catch(err: any) {
        data[model] = {
          hits: {
            hits: []
          }
        }
      }
    }
  } catch(error: any) {
    data = errorHandlingHelper(error, error)
  }
  
  // Now you can use defaultSideBarMenu anywhere in your processing logic
  //console.log('Processing with defaultSideBarMenu:', defaultSideBarMenu)

  return data
})