import { api } from './common'

/**
 * Get document info (pageinfo) including timeline data.
 * Aligns with old frontend: jingrow.desk.form.load.get_pageinfo
 */
export async function getPageinfo(pagetype: string, name: string): Promise<any> {
  const result = await api.call('jingrow.desk.form.load.get_pageinfo', { pagetype, name })
  // api.call returns response.data; get_pageinfo puts data in jingrow.response["pageinfo"]
  // so the actual pageinfo is at result.pageinfo, with fallback to result.message
  return result.pageinfo || result.message || result
}

/**
 * Toggle like on a document.
 * Aligns with old frontend: jingrow.desk.like.toggle_like
 * @param add - 'Yes' to like, 'No' to unlike
 */
export async function toggleLike(pagetype: string, name: string, add: 'Yes' | 'No'): Promise<void> {
  await api.call('jingrow.desk.like.toggle_like', { pagetype, name, add })
}

/**
 * Add a comment to a document.
 * Aligns with old frontend: jingrow.desk.form.utils.add_comment
 */
export async function addComment(
  referencePagetype: string,
  referenceName: string,
  content: string,
  commentEmail?: string,
  commentBy?: string
): Promise<any> {
  const result = await api.call('jingrow.desk.form.utils.add_comment', {
    reference_pagetype: referencePagetype,
    reference_name: referenceName,
    content,
    comment_email: commentEmail || '',
    comment_by: commentBy || '',
  })
  return result.message || result
}

/**
 * Update a comment's content.
 * Aligns with old frontend: jingrow.desk.form.utils.update_comment
 */
export async function updateComment(name: string, content: string): Promise<any> {
  const result = await api.call('jingrow.desk.form.utils.update_comment', { name, content })
  return result.message || result
}

/**
 * Delete a comment.
 * Uses the generic jingrow.client.delete RPC.
 */
export async function deleteComment(name: string): Promise<void> {
  await api.call('jingrow.client.delete', { pagetype: 'Comment', name })
}
