import api from "./client";
import type {
  BookDetail,
  BookListItem,
  BookSearchParams,
  ContentResponse,
  EBookDetail,
  EBookListItem,
  ReadingProgress,
  ReadingSettings,
  TocResponse,
} from "../types/book";

export const booksApi = {
  async getEBooks(): Promise<EBookListItem[]> {
    const { data } = await api.get<{ count: number; results: EBookListItem[] } | EBookListItem[]>("/books/ebooks/");
    if (Array.isArray(data)) return data;
    return data.results ?? [];
  },

  async getEBook(id: number): Promise<EBookDetail> {
    const { data } = await api.get<EBookDetail>(`/books/ebooks/${id}/`);
    return data;
  },

  async getEpubFile(id: number): Promise<Blob> {
    const { data } = await api.get<Blob>(`/books/ebooks/${id}/file/`, {
      responseType: "blob",
    });
    return data;
  },

  async searchBooks(params: BookSearchParams = {}): Promise<{ count: number; results: BookListItem[] }> {
    const { data } = await api.get<{ count: number; results: BookListItem[] } | BookListItem[]>("/books/", { params });
    if (Array.isArray(data)) {
      return { count: data.length, results: data };
    }
    return { count: data.count ?? 0, results: data.results ?? [] };
  },

  async getBook(id: number): Promise<BookDetail> {
    const { data } = await api.get<BookDetail>(`/books/${id}/`);
    return data;
  },

  async getGenres(): Promise<string[]> {
    const { data } = await api.get<string[]>("/books/genres/");
    return data;
  },

  async getAuthors(): Promise<string[]> {
    const { data } = await api.get<string[]>("/books/authors/");
    return data;
  },

  async uploadEBook(
    file: File,
    title: string,
    author: string,
    coverImage?: File | null,
  ): Promise<EBookDetail> {
    const formData = new FormData();
    formData.append("file", file);
    formData.append("title", title);
    if (author) formData.append("author", author);
    if (coverImage) formData.append("cover_image", coverImage);

    const { data } = await api.post<EBookDetail>("/books/ebooks/", formData, {
      headers: { "Content-Type": "multipart/form-data" },
    });
    return data;
  },

  async deleteEBook(id: number): Promise<void> {
    await api.delete(`/books/ebooks/${id}/`);
  },

  async enrichEBookMetadata(id: number): Promise<EBookDetail> {
    const { data } = await api.post<EBookDetail>(`/books/ebooks/${id}/enrich-metadata/`);
    return data;
  },

  async processEBook(id: number): Promise<{ status: string }> {
    const { data } = await api.post<{ status: string }>(`/books/ebooks/${id}/process/`);
    return data;
  },

  async getToc(id: number): Promise<TocResponse> {
    const { data } = await api.get<TocResponse>(`/books/ebooks/${id}/toc/`);
    return data;
  },

  async getContent(id: number, page: number): Promise<ContentResponse> {
    const { data } = await api.get<ContentResponse>(`/books/ebooks/${id}/content/?page=${page}`);
    return data;
  },

  async getProgress(ebookId: number): Promise<ReadingProgress> {
    const { data } = await api.get<ReadingProgress>(`/books/ebooks/${ebookId}/progress/`);
    return data;
  },

  async updateProgress(ebookId: number, progressData: Partial<ReadingProgress>): Promise<ReadingProgress> {
    const { data } = await api.patch<ReadingProgress>(`/books/ebooks/${ebookId}/progress/`, progressData);
    return data;
  },

  async getSettings(): Promise<ReadingSettings> {
    const { data } = await api.get<ReadingSettings>("/books/settings/");
    return data;
  },

  async updateSettings(settingsData: Partial<ReadingSettings>): Promise<ReadingSettings> {
    const { data } = await api.patch<ReadingSettings>("/books/settings/", settingsData);
    return data;
  },
};