import { string } from 'alga-js'
import getTokenHelper from "../../utils/getTokenHelper"
import { resolveOwnUserId } from "../../utils/merchantPartner"

// The calling mobile worker's own pending "pushed" tasks (tickets a dispatcher
// sent them via [id]/push-task.post.ts, waiting OR started, not completed) — oldest
// first. Consumed by the mobile dashboard's alert banner and by tasks.vue's
// pinned "Gepushte Aufgaben" section. Fails soft (empty list) if the custom
// columns IsPushedTask/PushedTaskAt don't exist yet in iDempiere.
const handleFunc = async (event: any, authToken: any = null) => {
  const token = authToken ?? await getTokenHelper(event)
  const userId = resolveOwnUserId(event)
  if (!userId) return { records: [] }

  const filter = string.urlEncode(
    `SalesRep_ID eq ${userId} AND IsPushedTask eq true AND IsComplete eq false`
  )
  const orderby = string.urlEncode('PushedTaskAt asc')
  const select = string.urlEncode(
    'DocumentNo,Name,Summary,AD_Org_ID,C_BPartner_ID,Priority,PushedTaskAt,Created,QtySpent,RequestAmt,TaskStatus,C_Order_ID,M_Product_ID,M_InOut_ID'
  )

  let records: any[] = []
  try {
    const res: any = await event.context.fetch(
      `models/r_request?$filter=${filter}&$orderby=${orderby}&$select=${select}&$top=100`,
      'GET', token, null
    )
    records = Array.isArray(res?.records) ? res.records : []
  } catch (e: any) {
    console.warn('[pushed-tasks] fetch failed (IsPushedTask/PushedTaskAt missing in iDempiere?):', e?.message)
    return { records: [] }
  }

  return {
    records: records.map((r: any) => ({
      id: r.id,
      documentNo: r.DocumentNo || String(r.id),
      name: r.Name || '',
      summary: r.Summary || '',
      orgId: r.AD_Org_ID?.id || '',
      orgName: r.AD_Org_ID?.identifier || '',
      bpartnerName: r.C_BPartner_ID?.identifier || '',
      priorityId: r.Priority?.id || '',
      priorityLabel: r.Priority?.identifier || '',
      pushedTaskAt: r.PushedTaskAt || r.pushedTaskAt || null,
      created: r.Created,
      isComplete: false,
      // TaskStatus '0' (or unset) = pushed & waiting; anything else = the
      // worker has started it (push-task-status.post.ts 'start').
      taskStatus: r.TaskStatus?.id || '0',
      started: !!(r.TaskStatus?.id && r.TaskStatus.id !== '0'),
      // Linked order / product — rendered as cards in the worker's modal so
      // the instruction has its context without opening the full history.
      orderId: r.C_Order_ID?.id || '',
      orderDocNo: r.C_Order_ID?.identifier || '',
      productId: r.M_Product_ID?.id || '',
      productName: r.M_Product_ID?.identifier || '',
      inOutId: r.M_InOut_ID?.id || '',
      inOutDocNo: r.M_InOut_ID?.identifier || '',
      qtySpent: Number(r.QtySpent) || 0,
      requestAmt: Number(r.RequestAmt) || 0
    }))
  }
}

export default defineEventHandler((event) => withAuthRetry(event, handleFunc))
