/**
 * Thin publisher API helpers over the existing research endpoints.
 *
 * Papers have no dedicated backend: they live in `ResearchProject.content.papers[]`, read via the
 * cockpit bundle and written via the merge endpoint (which records an audit row server-side, INV-6).
 * There is no per-paper endpoint, so saving is read-modify-write of the whole array.
 */
import {
  getCockpit,
  listMyProjects,
  updateProjectDetail,
  type CockpitBundle,
  type ResearchProject,
} from '@ump/shared';

import { extractPapers, type Paper } from '../domain/paperModel';

/** Approved projects the investigator owns — the publishable research-result sources. */
export async function listPublishableProjects(): Promise<ResearchProject[]> {
  const projects = await listMyProjects();
  return projects.filter((p) => p.status === 'approved');
}

export interface ProjectResearch {
  bundle: CockpitBundle;
  papers: Paper[];
}

/** Read a project's full research results (cockpit) plus its current papers. */
export async function getProjectResearch(projectId: string): Promise<ProjectResearch> {
  const bundle = await getCockpit(projectId);
  return { bundle, papers: extractPapers(bundle.project.content) };
}

/**
 * Persist the whole papers array into `content.papers[]` via the merge endpoint.
 * Returns the updated project.
 */
export function savePapers(projectId: string, papers: Paper[]): Promise<ResearchProject> {
  return updateProjectDetail(projectId, { papers });
}
