// services/milestoneService.ts
const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8080';

export interface Milestone {
  id: number;
  title: string;
  description: string;
  displayOrder: number;
  isActive: boolean;
  milestoneDate: string | null;
  createdAt: string;
  updatedAt: string;
}

/**
 * Fetch all active milestones from the API
 * Uses the public endpoint that doesn't require authentication
 */
export async function getActiveMilestones(): Promise<Milestone[]> {
  try {
    const response = await fetch(`${API_BASE_URL}/api/milestones/public`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
      },
      cache: 'no-store', // Disable caching for fresh data
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const data = await response.json();
    return data;
  } catch (error) {
    console.error('Error fetching milestones:', error);
    // Return empty array as fallback
    return [];
  }
}

/**
 * Fetch all milestones (requires authentication)
 */
export async function getAllMilestones(token?: string): Promise<Milestone[]> {
  try {
    const headers: HeadersInit = {
      'Content-Type': 'application/json',
    };

    if (token) {
      headers['Authorization'] = `Bearer ${token}`;
    }

    const response = await fetch(`${API_BASE_URL}/api/milestones`, {
      method: 'GET',
      headers,
      cache: 'no-store',
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const data = await response.json();
    return data;
  } catch (error) {
    console.error('Error fetching all milestones:', error);
    return [];
  }
}