// Service worker. Receives envelopes from content scripts, POSTs them
// to the admin host with the bearer token stored in extension options.

const TAG = '[linkedin-ext-post]'

async function getConfig() {
  const stored = await chrome.storage.local.get(['adminHost', 'sessionKey'])
  return {
    adminHost: typeof stored.adminHost === 'string' ? stored.adminHost.replace(/\/+$/, '') : '',
    sessionKey: typeof stored.sessionKey === 'string' ? stored.sessionKey : '',
  }
}

async function postEnvelope(envelope) {
  const { adminHost, sessionKey } = await getConfig()
  if (!adminHost) return { ok: false, reason: 'auth', detail: 'admin-host-missing' }
  if (!sessionKey) return { ok: false, reason: 'auth', detail: 'session-key-missing' }

  const url = adminHost + '/api/admin/linkedin-ingest'
  const started = Date.now()
  let res
  try {
    res = await fetch(url, {
      method: 'POST',
      headers: { 'content-type': 'application/json' },
      body: JSON.stringify({ ...envelope, session_key: sessionKey }),
    })
  } catch (err) {
    console.error(TAG + ' dispatchId=' + envelope.dispatchId + ' status=network ms=' + (Date.now() - started))
    return { ok: false, reason: 'network', detail: err && err.message ? err.message : String(err) }
  }

  const ms = Date.now() - started
  console.log(TAG + ' dispatchId=' + envelope.dispatchId + ' status=' + res.status + ' ms=' + ms)

  if (res.status === 401) return { ok: false, reason: 'auth', detail: 'session-rejected' }
  if (res.status >= 500) return { ok: false, reason: 'server', detail: 'http-' + res.status }
  if (!res.ok) {
    let body = ''
    try { body = await res.text() } catch { /* ignore */ }
    return { ok: false, reason: 'extract', detail: 'http-' + res.status + (body ? ' ' + body.slice(0, 200) : '') }
  }

  return { ok: true }
}

chrome.runtime.onMessage.addListener(function (msg, _sender, sendResponse) {
  if (!msg || msg.type !== 'linkedin-ingest' || !msg.envelope) {
    sendResponse({ ok: false, reason: 'extract', detail: 'bad-message' })
    return false
  }
  postEnvelope(msg.envelope).then(sendResponse).catch(function (err) {
    sendResponse({ ok: false, reason: 'extract', detail: err && err.message ? err.message : String(err) })
  })
  return true // async sendResponse
})

chrome.action.onClicked.addListener(function () {
  chrome.runtime.openOptionsPage()
})
