/**
 * API client for the reader module — reading settings and progress.
 * Uses the shared axios client so JWT auth is attached automatically.
 */

import api from "./client";
import type { ReadingProgress, ReadingSettings } from "../types/reader";

export async function getReadingSettings(): Promise<ReadingSettings> {
  const { data } = await api.get<ReadingSettings>("/reader/settings/");
  return data;
}

export async function updateReadingSettings(
  settings: Partial<ReadingSettings>,
): Promise<ReadingSettings> {
  const { data } = await api.patch<ReadingSettings>("/reader/settings/", settings);
  return data;
}

export async function getReadingProgress(
  bookId: number,
): Promise<ReadingProgress> {
  const { data } = await api.get<{
    current_position: number;
    last_page: number;
    epub_location?: string;
    updated_at?: string;
  }>(`/books/ebooks/${bookId}/progress/`);
  return {
    id: bookId,
    book: bookId,
    current_chapter: data.last_page || 1,
    current_position: data.current_position ?? 0,
    percentage: data.current_position ?? 0,
    epub_location: data.epub_location ?? "",
    updated_at: data.updated_at ?? "",
  };
}

export async function updateReadingProgress(
  bookId: number,
  progress: Partial<ReadingProgress>,
): Promise<ReadingProgress> {
  const body: Record<string, string | number> = {};
  if (progress.percentage !== undefined || progress.current_position !== undefined) {
    body.current_position = progress.percentage ?? progress.current_position ?? 0;
  }
  if (progress.current_chapter !== undefined) {
    body.last_page = progress.current_chapter;
  }
  if (progress.epub_location !== undefined) {
    body.epub_location = progress.epub_location;
  }
  const { data } = await api.patch<{
    current_position: number;
    last_page: number;
    epub_location?: string;
    updated_at?: string;
  }>(`/books/ebooks/${bookId}/progress/`, body);
  return {
    id: bookId,
    book: bookId,
    current_chapter: data.last_page || 1,
    current_position: data.current_position ?? 0,
    percentage: data.current_position ?? 0,
    epub_location: data.epub_location ?? "",
    updated_at: data.updated_at ?? "",
  };
}
