import { apiRequest } from './api.js'

const AUTH_USER_STORAGE_KEY = 'x-financial-auth-user'

function readActorName() {
  if (typeof window === 'undefined') {
    return 'system'
  }

  const raw = window.sessionStorage.getItem(AUTH_USER_STORAGE_KEY)
  if (!raw) {
    return 'system'
  }

  try {
    const payload = JSON.parse(raw)
    return String(payload?.name || payload?.username || 'system').trim() || 'system'
  } catch {
    return 'system'
  }
}

function buildWriteHeaders(options = {}) {
  const actor = String(options.actor || readActorName()).trim() || 'system'
  const headers = {
    'x-actor': actor
  }

  if (options.requestId) {
    headers['x-request-id'] = String(options.requestId).trim()
  }

  return headers
}

function buildQuery(params = {}) {
  const search = new URLSearchParams()

  if (params.assetType) {
    search.set('asset_type', params.assetType)
  }

  if (params.status) {
    search.set('status', params.status)
  }

  if (params.domain) {
    search.set('domain', params.domain)
  }

  if (params.keyword) {
    search.set('keyword', params.keyword)
  }

  if (params.limit) {
    search.set('limit', String(params.limit))
  }

  if (params.agent) {
    search.set('agent', params.agent)
  }

  if (params.source) {
    search.set('source', params.source)
  }

  const query = search.toString()
  return query ? `?${query}` : ''
}

export function fetchAgentAssets(params = {}) {
  return apiRequest(`/agent-assets${buildQuery(params)}`)
}

export function fetchAgentAssetDetail(assetId) {
  return apiRequest(`/agent-assets/${assetId}`)
}

export function fetchAgentAssetVersions(assetId, limit = 5) {
  return apiRequest(`/agent-assets/${assetId}/versions${buildQuery({ limit })}`)
}

export function updateAgentAsset(assetId, payload, options = {}) {
  return apiRequest(`/agent-assets/${assetId}`, {
    method: 'PATCH',
    body: JSON.stringify(payload),
    headers: buildWriteHeaders(options)
  })
}

export function createAgentAssetVersion(assetId, payload, options = {}) {
  return apiRequest(`/agent-assets/${assetId}/versions`, {
    method: 'POST',
    body: JSON.stringify(payload),
    headers: buildWriteHeaders(options)
  })
}

export function createAgentAssetReview(assetId, payload, options = {}) {
  return apiRequest(`/agent-assets/${assetId}/reviews`, {
    method: 'POST',
    body: JSON.stringify(payload),
    headers: buildWriteHeaders(options)
  })
}

export function activateAgentAsset(assetId, options = {}) {
  return apiRequest(`/agent-assets/${assetId}/activate`, {
    method: 'POST',
    headers: buildWriteHeaders(options)
  })
}

export function fetchAgentRuns(params = {}) {
  return apiRequest(`/agent-runs${buildQuery(params)}`)
}
