/**
 * POST /api/settings/software-catalog/seed-lists  (staff only)
 * Fills the five AD_Reference lists (SOFTWARE_REF_LISTS) with their missing
 * AD_Ref_List values. AD_Ref_List is a System-level table, so a client role
 * usually gets "Access denied" — the response then lists the Value/Name pairs
 * to enter by hand (or run reference/test-scripts/software-catalog-seed-lists.mts
 * / the SQL variant). Idempotent: existing values are never touched.
 */
import { gateFromEvent } from '../../../utils/chatAccess'
import fetchHelper from '../../../utils/fetchHelper'
import { SOFTWARE_REF_LISTS } from '../../../../app/utils/softwareCatalogDefaults'

export default defineEventHandler(async (event) => {
  const { token } = await gateFromEvent(event, { requireChat: false })
  const report: any[] = []
  for (const [refName, values] of Object.entries(SOFTWARE_REF_LISTS)) {
    const entry: any = { reference: refName, created: [], present: [], failed: [] }
    try {
      const ref: any = await fetchHelper(event, `models/ad_reference?$filter=${encodeURIComponent(`Name eq '${refName}'`)}&$top=1`, 'GET', token, null)
      const refId = Number(ref?.records?.[0]?.id)
      if (!refId) { entry.error = 'reference not found'; report.push(entry); continue }
      const existing: any = await fetchHelper(event, `models/ad_ref_list?$filter=${encodeURIComponent(`AD_Reference_ID eq ${refId}`)}&$top=100`, 'GET', token, null)
      const have = new Set((existing?.records || []).map((r: any) => String(r.Value ?? r.value)))
      for (const v of values) {
        if (have.has(v.value)) { entry.present.push(v.value); continue }
        try {
          await fetchHelper(event, 'models/ad_ref_list', 'POST', token, { AD_Reference_ID: { id: refId }, value: v.value, name: v.name, entityType: 'U' })
          entry.created.push(v.value)
        } catch (e: any) {
          entry.failed.push({ value: v.value, name: v.name, error: e?.data?.detail || e?.message || String(e) })
        }
      }
    } catch (e: any) {
      entry.error = e?.data?.detail || e?.message || String(e)
    }
    report.push(entry)
  }
  const failed = report.some((r) => r.error || r.failed.length)
  return { status: failed ? 207 : 200, report }
})
