import { Pool } from 'pg'
import refreshTokenHelper from "../../utils/refreshTokenHelper"

const handleFunc = async (event: any) => {
  const config = useRuntimeConfig()
  const dbConfig = {
    host: config.pgHost,
    port: parseInt(config.pgPort || '5432'),
    database: config.pgDatabase,
    user: config.pgUser,
    password: config.pgPassword,
  }

  if (!dbConfig.host || !dbConfig.database || !dbConfig.user || !dbConfig.password) {
    throw createError({
      statusCode: 500,
      message: 'PostgreSQL credentials not configured. Please set PG_HOST, PG_DATABASE, PG_USER, PG_PASSWORD in .env'
    })
  }

  // Limited roles (FrontendMenu == 'c') only see their own organization. Admins
  // see all orgs (NULL filter is a no-op in the SQL below).
  const roleCookie = getCookie(event, 'logship_role')
  let menuType: string = 'Menu'
  try {
    const role = roleCookie ? JSON.parse(roleCookie) : null
    menuType = role?.FrontendMenu?.id || role?.FrontendMenu || 'Menu'
  } catch {}
  const orgIdCookie = getCookie(event, 'logship_organization_id')
  const orgIdNum = orgIdCookie ? parseInt(orgIdCookie) : NaN
  const orgFilter: number | null = (menuType === 'c' && Number.isFinite(orgIdNum)) ? orgIdNum : null

  const pool = new Pool(dbConfig)

  try {
    const sql = `
      WITH stock AS (
        SELECT s.m_product_id,
               l.m_warehouse_id,
               SUM(s.qtyonhand) AS qtyonhand
        FROM m_storage s
        JOIN m_locator l ON l.m_locator_id = s.m_locator_id
        LEFT JOIN m_locatortype lt ON lt.m_locatortype_id = l.m_locatortype_id
        WHERE lt.m_locatortype_id IS NULL
           OR lt.isavailableforshipping = 'Y'
           OR lt.isavailableforreplenishment = 'Y'
           OR lt.isavailableforreservation = 'Y'
        GROUP BY s.m_product_id, l.m_warehouse_id
      ),
      -- An order is unfulfillable when for ANY of its products the SUMMED open
      -- demand of the order exceeds the warehouse stock. Comparing per line
      -- (the previous version) missed orders whose demand for one product is
      -- split across several lines each individually below stock.
      unfulfillable AS (
        SELECT DISTINCT g.c_order_id, g.ad_org_id
        FROM (
          SELECT o.c_order_id, o.ad_org_id
          FROM c_order o
          JOIN c_orderline ol ON ol.c_order_id = o.c_order_id
          JOIN m_product   p  ON p.m_product_id = ol.m_product_id
          LEFT JOIN stock st
            ON st.m_product_id = ol.m_product_id
           AND st.m_warehouse_id = o.m_warehouse_id
          WHERE o.issotrx = 'Y'
            AND o.docstatus IN ('CO','CL')
            AND o.ad_client_id = 1000000
            AND o.isfulfillmentorder = 'Y'
            AND ($1::int IS NULL OR o.ad_org_id = $1)
            AND ol.m_product_id IS NOT NULL
            AND p.producttype = 'I'
            AND (ol.qtyordered - COALESCE(ol.qtydelivered, 0)) > 0
            AND NOT EXISTS (
                  SELECT 1
                  FROM m_inout io
                  JOIN m_inoutline iol ON iol.m_inout_id = io.m_inout_id
                  WHERE io.c_order_id = o.c_order_id
                    AND io.issotrx = 'Y'
                    AND io.docstatus NOT IN ('VO','RE')
            )
          GROUP BY o.c_order_id, o.ad_org_id, ol.m_product_id
          HAVING SUM(ol.qtyordered - COALESCE(ol.qtydelivered, 0)) > COALESCE(MAX(st.qtyonhand), 0)
        ) g
      )
      SELECT
        COALESCE(org.name, 'Unknown') AS org_name,
        COUNT(*) AS count_per_org
      FROM unfulfillable u
      LEFT JOIN ad_org org ON org.ad_org_id = u.ad_org_id
      GROUP BY org.name
      ORDER BY count_per_org DESC
    `

    const result = await pool.query(sql, [orgFilter])

    const byOrg = result.rows.map((r: any) => ({
      org: r.org_name,
      count: parseInt(r.count_per_org || 0)
    }))
    const total = byOrg.reduce((acc, r) => acc + r.count, 0)

    return {
      count: total,
      byOrg
    }
  } catch (err: any) {
    console.error('PostgreSQL query error:', err)
    throw createError({
      statusCode: 500,
      message: `Database error: ${err.message}`
    })
  } finally {
    await pool.end()
  }
}

export default defineEventHandler(async (event) => {
  try {
    return await handleFunc(event)
  } catch(err: any) {
    try {
      let authToken: any = await refreshTokenHelper(event)
      return await handleFunc(event)
    } catch(error: any) {
      console.error('Fatal error in unfulfillable-count:', error)
      throw error
    }
  }
})
