import { api, API_BASE_URL } from "@/lib/api-client";
import { asPaginated, asRecordData } from "@/lib/odoo-api";
import type { Resource, ResourceCompletion, PaginatedResponse, PaginationParams, ApiSuccessResponse } from "@/types";

export interface ResourceListParams extends PaginationParams {
  topic_id?: number;
  resource_type?: string;
  review_status?: string;
  search?: string;
}

export const resourcesService = {
  async list(params?: ResourceListParams): Promise<PaginatedResponse<Resource>> {
    const raw = await api.get<unknown>("/resources", params as Record<string, string | number | boolean | undefined>);
    return asPaginated<Resource>(raw);
  },

  async upload(formData: FormData): Promise<Resource> {
    const raw = await api.upload<unknown>("/resources", formData);
    return asRecordData<Resource>(raw);
  },

  async update(id: number, data: Partial<Resource>): Promise<Resource> {
    const raw = await api.patch<unknown>(`/resources/${id}`, data);
    return asRecordData<Resource>(raw);
  },

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

  async markComplete(id: number): Promise<ResourceCompletion> {
    const raw = await api.post<unknown>(`/resources/${id}/complete`);
    return asRecordData<ResourceCompletion>(raw);
  },

  async rate(id: number, rating: number): Promise<ApiSuccessResponse> {
    return api.post<ApiSuccessResponse>(`/resources/${id}/rate`, { rating });
  },

  async download(id: number): Promise<Blob> {
    const res = await fetch(`${API_BASE_URL}/resources/${id}/download`, {
      headers: { Authorization: `Bearer ${localStorage.getItem("encoach_token") ?? ""}` },
    });
    if (!res.ok) throw new Error(`Download failed: ${res.status} ${res.statusText}`);
    return res.blob();
  },
};
