import { api } from "@/lib/api-client";
import type { Subject, Domain, Topic, LearningObjective, TaxonomyTree, PaginatedResponse, PaginationParams, ApiSuccessResponse } from "@/types";

export const taxonomyService = {
  async listSubjects(): Promise<Subject[]> {
    const res = await api.get<{ data: Subject[] } | Subject[]>("/subjects");
    return Array.isArray(res) ? res : (res as { data: Subject[] }).data ?? [];
  },

  async getSubject(id: number): Promise<Subject> {
    const res = await api.get<{ data: Subject } | Subject>(`/subjects/${id}`);
    return (res as { data: Subject }).data ?? res;
  },

  async createSubject(data: Partial<Subject>): Promise<Subject> {
    return api.post<Subject>("/subjects", data);
  },

  async updateSubject(id: number, data: Partial<Subject>): Promise<Subject> {
    return api.patch<Subject>(`/subjects/${id}`, data);
  },

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

  async getTaxonomyTree(subjectId: number): Promise<TaxonomyTree> {
    const res = await api.get<{ data: TaxonomyTree } | TaxonomyTree>(`/subjects/${subjectId}/taxonomy`);
    return (res as { data: TaxonomyTree }).data ?? res;
  },

  async importTaxonomy(subjectId: number, data: FormData): Promise<ApiSuccessResponse> {
    return api.upload<ApiSuccessResponse>(`/subjects/${subjectId}/taxonomy/import`, data);
  },

  async listDomains(params?: { subject_id?: number }): Promise<Domain[]> {
    const res = await api.get<{ data: Domain[] } | Domain[]>("/domains", params as Record<string, string | number | boolean | undefined>);
    return Array.isArray(res) ? res : (res as { data: Domain[] }).data ?? [];
  },

  async createDomain(data: Partial<Domain>): Promise<Domain> {
    return api.post<Domain>("/domains", data);
  },

  async updateDomain(id: number, data: Partial<Domain>): Promise<Domain> {
    return api.patch<Domain>(`/domains/${id}`, data);
  },

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

  async aiSuggestTopics(domainId: number): Promise<{ suggestions: Partial<Topic>[] }> {
    return api.post(`/domains/${domainId}/ai-suggest`);
  },

  async listTopics(params?: { domain_id?: number; subject_id?: number }): Promise<Topic[]> {
    const res = await api.get<{ data: Topic[] } | Topic[]>("/topics", params as Record<string, string | number | boolean | undefined>);
    return Array.isArray(res) ? res : (res as { data: Topic[] }).data ?? [];
  },

  async createTopic(data: Partial<Topic>): Promise<Topic> {
    return api.post<Topic>("/topics", data);
  },

  async updateTopic(id: number, data: Partial<Topic>): Promise<Topic> {
    return api.patch<Topic>(`/topics/${id}`, data);
  },

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