/**
 * GET /api/surveillance/cameras
 *
 * Lists the Surveillance Station cameras as `{ id, name }` so staff can find
 * each camera's id when configuring CUST_CommissionTable.synology_camera_id.
 * Open it in the browser, or it backs the camera dropdown in the
 * commission-table form. Staff-only (mirrors the limited-role guard used by
 * the shipment-recording endpoints).
 */

import { synologyLogin, synologyLogout, synologyListCameras } from '../../utils/synologyHelper'

function isLimitedRole(event: any): boolean {
  try {
    const raw = getCookie(event, 'logship_role')
    if (!raw) return false
    const role = JSON.parse(raw)
    const fm = role?.FrontendMenu
    const id = typeof fm === 'object' ? (fm?.id ?? fm?.identifier) : fm
    return String(id || '').toLowerCase() === 'c'
  } catch {
    return false
  }
}

export default defineEventHandler(async (event) => {
  if (isLimitedRole(event)) {
    throw createError({ statusCode: 403, statusMessage: 'Not allowed for this role.' })
  }

  const session = await synologyLogin()
  try {
    const cameras = await synologyListCameras(session)
    return { cameras }
  } finally {
    await synologyLogout(session)
  }
})
