import { apiClient } from '@/lib/api-client';
import type {
  OnlineLessonByIdResponse,
  OnlineLessonFilters,
  OnlineLessonMutationPayload,
  OnlineLessonWorkflowActionPayload,
  OnlineLessonsResponse
} from './types';

export function buildOnlineLessonSearchParams(filters: OnlineLessonFilters) {
  const searchParams = new URLSearchParams();

  if (filters.page) searchParams.set('page', String(filters.page));
  if (filters.limit) searchParams.set('limit', String(filters.limit));
  if (filters.search) searchParams.set('search', filters.search);
  if (filters.status) searchParams.set('status', filters.status);
  if (filters.category) searchParams.set('category', filters.category);

  return searchParams;
}

function buildOnlineLessonFormData(data: OnlineLessonMutationPayload) {
  const formData = new FormData();

  formData.set('title', data.title);
  formData.set('description', data.description ?? '');
  formData.set('category', data.category ?? '');
  formData.set('videoUrl', data.videoUrl ?? '');
  formData.set('action', data.action ?? 'draft');
  formData.set('removeVideoFile', String(Boolean(data.removeVideoFile)));
  formData.set('removeAttachment', String(Boolean(data.removeAttachment)));
  formData.set('removeThumbnail', String(Boolean(data.removeThumbnail)));

  if (data.videoFile) {
    formData.set('videoFile', data.videoFile);
  }

  if (data.attachmentFile) {
    formData.set('attachmentFile', data.attachmentFile);
  }

  if (data.thumbnailFile) {
    formData.set('thumbnailFile', data.thumbnailFile);
  }

  return formData;
}

export async function getOnlineLessons(filters: OnlineLessonFilters): Promise<OnlineLessonsResponse> {
  const searchParams = buildOnlineLessonSearchParams(filters);
  return apiClient<OnlineLessonsResponse>(`/online-lessons?${searchParams.toString()}`);
}

export async function getOnlineLessonById(id: number): Promise<OnlineLessonByIdResponse> {
  return apiClient<OnlineLessonByIdResponse>(`/online-lessons/${id}`);
}

export async function createOnlineLesson(data: OnlineLessonMutationPayload) {
  return apiClient<OnlineLessonByIdResponse>('/online-lessons', {
    method: 'POST',
    body: buildOnlineLessonFormData(data)
  });
}

export async function updateOnlineLesson(id: number, data: OnlineLessonMutationPayload) {
  return apiClient<OnlineLessonByIdResponse>(`/online-lessons/${id}`, {
    method: 'PATCH',
    body: buildOnlineLessonFormData(data)
  });
}

export async function updateOnlineLessonState(
  id: number,
  data: OnlineLessonWorkflowActionPayload
) {
  return apiClient<OnlineLessonByIdResponse>(`/online-lessons/${id}`, {
    method: 'PATCH',
    body: JSON.stringify(data)
  });
}

export async function deleteOnlineLesson(id: number) {
  return apiClient<{ success: boolean; message: string }>(`/online-lessons/${id}`, {
    method: 'DELETE'
  });
}
