import { api, API_BASE_URL } from "@/lib/api-client";
import type {
  CourseChapter,
  ChapterMaterial,
  ChapterProgress,
  ChapterCreateRequest,
  WorkbenchGenerateRequest,
  WorkbenchGeneratedOutline,
  WorkbenchGeneratedChapter,
} from "@/types/courseware";
import type { ApiSuccessResponse } from "@/types";

const blobDownloadHeaders = (): Record<string, string> => ({
  Authorization: `Bearer ${localStorage.getItem("encoach_token") ?? ""}`,
});

export const coursewareService = {
  async listChapters(courseId: number): Promise<CourseChapter[]> {
    return api.get<CourseChapter[]>(`/courses/${courseId}/chapters`);
  },

  async createChapter(courseId: number, data: ChapterCreateRequest): Promise<CourseChapter> {
    return api.post<CourseChapter>(`/courses/${courseId}/chapters`, data);
  },

  async getChapter(id: number): Promise<CourseChapter> {
    return api.get<CourseChapter>(`/chapters/${id}`);
  },

  async updateChapter(id: number, data: Partial<ChapterCreateRequest>): Promise<CourseChapter> {
    return api.patch<CourseChapter>(`/chapters/${id}`, data);
  },

  async deleteChapter(id: number): Promise<ApiSuccessResponse> {
    return api.delete<ApiSuccessResponse>(`/chapters/${id}`);
  },

  async unlockChapter(id: number): Promise<ApiSuccessResponse> {
    return api.post<ApiSuccessResponse>(`/chapters/${id}/unlock`);
  },

  async lockChapter(id: number): Promise<ApiSuccessResponse> {
    return api.post<ApiSuccessResponse>(`/chapters/${id}/lock`);
  },

  async reorderChapters(courseId: number, body: { ids: number[] }): Promise<ApiSuccessResponse> {
    return api.patch<ApiSuccessResponse>(`/courses/${courseId}/chapters/reorder`, body);
  },

  async getChapterProgress(id: number): Promise<ChapterProgress> {
    return api.get<ChapterProgress>(`/chapters/${id}/progress`);
  },

  async markChapterComplete(id: number): Promise<ApiSuccessResponse> {
    return api.post<ApiSuccessResponse>(`/chapters/${id}/progress/complete`);
  },

  async listMaterials(chapterId: number): Promise<ChapterMaterial[]> {
    return api.get<ChapterMaterial[]>(`/chapters/${chapterId}/materials`);
  },

  async uploadMaterial(chapterId: number, formData: FormData): Promise<ChapterMaterial> {
    return api.upload<ChapterMaterial>(`/chapters/${chapterId}/materials`, formData);
  },

  async updateMaterial(id: number, data: Partial<ChapterMaterial>): Promise<ChapterMaterial> {
    return api.patch<ChapterMaterial>(`/materials/${id}`, data);
  },

  async deleteMaterial(id: number): Promise<ApiSuccessResponse> {
    return api.delete<ApiSuccessResponse>(`/materials/${id}`);
  },

  async downloadMaterial(id: number): Promise<Blob> {
    const res = await fetch(`${API_BASE_URL}/materials/${id}/download`, {
      headers: blobDownloadHeaders(),
    });
    if (!res.ok) throw new Error(`Download failed: ${res.status} ${res.statusText}`);
    return res.blob();
  },

  async markMaterialViewed(id: number): Promise<ApiSuccessResponse> {
    return api.post<ApiSuccessResponse>(`/materials/${id}/viewed`);
  },

  async reorderMaterials(chapterId: number, body: { ids: number[] }): Promise<ApiSuccessResponse> {
    return api.patch<ApiSuccessResponse>(`/chapters/${chapterId}/materials/reorder`, body);
  },

  async generateOutline(data: WorkbenchGenerateRequest): Promise<WorkbenchGeneratedOutline> {
    return api.post<WorkbenchGeneratedOutline>("/workbench/generate-outline", data);
  },

  async generateChapterContent(data: WorkbenchGenerateRequest): Promise<WorkbenchGeneratedChapter> {
    return api.post<WorkbenchGeneratedChapter>("/workbench/generate-chapter", data);
  },

  async generateRubric(data: WorkbenchGenerateRequest): Promise<{ rubric: string }> {
    return api.post("/workbench/generate-rubric", data);
  },

  async regenerateSection(data: Record<string, unknown>): Promise<WorkbenchGeneratedChapter> {
    return api.post<WorkbenchGeneratedChapter>("/workbench/regenerate", data);
  },

  async suggestMaterials(data: Record<string, unknown>): Promise<unknown> {
    return api.post("/workbench/suggest-materials", data);
  },

  async publishWorkbench(data: Record<string, unknown>): Promise<ApiSuccessResponse> {
    return api.post<ApiSuccessResponse>("/workbench/publish", data);
  },
};
