import { apiClient } from '@/lib/api-client';
import type {
  AnnouncementByIdResponse,
  AnnouncementFilters,
  AnnouncementMutationPayload,
  AnnouncementWorkflowActionPayload,
  AnnouncementsResponse
} from './types';

export function buildAnnouncementSearchParams(filters: AnnouncementFilters) {
  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.pin) searchParams.set('pin', filters.pin);
  if (filters.sort) searchParams.set('sort', filters.sort);

  return searchParams;
}

function buildAnnouncementFormData(data: AnnouncementMutationPayload) {
  const formData = new FormData();
  formData.set('title', data.title);
  formData.set('content', data.content);
  formData.set('startDate', data.startDate);
  formData.set('endDate', data.endDate ?? '');
  formData.set('action', data.action);
  formData.set('removeAttachment', String(Boolean(data.removeAttachment)));

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

  return formData;
}

export async function getAnnouncements(filters: AnnouncementFilters): Promise<AnnouncementsResponse> {
  const searchParams = buildAnnouncementSearchParams(filters);
  return apiClient<AnnouncementsResponse>(`/announcements?${searchParams.toString()}`);
}

export async function getAnnouncementById(id: number): Promise<AnnouncementByIdResponse> {
  return apiClient<AnnouncementByIdResponse>(`/announcements/${id}`);
}

export async function createAnnouncement(data: AnnouncementMutationPayload) {
  return apiClient<AnnouncementByIdResponse>('/announcements', {
    method: 'POST',
    body: buildAnnouncementFormData(data)
  });
}

export async function updateAnnouncement(id: number, data: AnnouncementMutationPayload) {
  return apiClient<AnnouncementByIdResponse>(`/announcements/${id}`, {
    method: 'PATCH',
    body: buildAnnouncementFormData(data)
  });
}

export async function updateAnnouncementState(
  id: number,
  data: AnnouncementWorkflowActionPayload
) {
  return apiClient<AnnouncementByIdResponse>(`/announcements/${id}`, {
    method: 'PATCH',
    body: JSON.stringify(data)
  });
}

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

export async function pinAnnouncement(id: number) {
  return apiClient<{ success: boolean; message: string }>(`/announcements/${id}/pin`, {
    method: 'POST'
  });
}

export async function unpinAnnouncement(id: number) {
  return apiClient<{ success: boolean; message: string }>(`/announcements/${id}/unpin`, {
    method: 'POST'
  });
}
