// services/educationService.ts
export interface ApiCourse {
  id: number;
  title: string;
  description: string;
  duration: string;
  seats: number;
  category: string;
  level: string;
  instructor: string;
  price?: string;
  startDate?: string;
  imageUrl?: string;
  eligibility: string[];
  objectives: string[];
  isActive: boolean;
  createdDate?: string;
  updatedDate?: string;
}

export interface Course {
  id: string;
  title: string;
  description: string;
  duration: string;
  seats: number;
  category: string;
  level: string;
  instructor: string;
  price: string;
  startDate: string;
  image: string;
  eligibility: string[];
  objectives: string[];
}

export interface CourseApplicationData {
  courseId: number;
  fullName: string;
  email: string;
  phone: string;
  qualification: string;
  experience?: string;
  coverLetter?: string;
  resumeUrl?: string;
}

class EducationService {
  private apiBaseUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8080';

  // Helper method to convert relative URLs to absolute URLs
  private getFullImageUrl(imageUrl: string | undefined): string {
    if (!imageUrl || imageUrl.trim() === '') {
      return this.getRandomDefaultImage();
    }
    
    // If it's already a full URL, return as-is
    if (imageUrl.startsWith('http://') || imageUrl.startsWith('https://')) {
      return imageUrl;
    }
    
    // If it's a relative URL, prepend the backend API URL
    const cleanUrl = imageUrl.startsWith('/') ? imageUrl.substring(1) : imageUrl;
    return `${this.apiBaseUrl}/${cleanUrl}`;
  }

  async getActiveCourses(): Promise<Course[]> {
    try {
      const response = await fetch(`${this.apiBaseUrl}/api/courses/active`, {
        cache: 'no-store'
      });
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      const apiCourses: ApiCourse[] = await response.json();
      return this.transformApiCoursesToCourses(apiCourses);
    } catch (error) {
      console.error('Error fetching courses:', error);
      return [];
    }
  }

  async getPastCourses(): Promise<Course[]> {
    try {
      const response = await fetch(`${this.apiBaseUrl}/api/courses/past`, {
        cache: 'no-store'
      });
      
      // If endpoint doesn't exist or returns 400/404, return empty array
      if (!response.ok) {
        if (response.status === 400 || response.status === 404) {
          console.log('Past courses endpoint not available, returning empty array');
          return [];
        }
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      
      const apiCourses: ApiCourse[] = await response.json();
      return this.transformApiCoursesToCourses(apiCourses);
    } catch (error) {
      console.error('Error fetching past courses:', error);
      // Return empty array instead of throwing error
      return [];
    }
  }

  async getCourseById(id: number): Promise<Course | null> {
    try {
      const token = typeof window !== 'undefined' ? localStorage.getItem('authToken') : null;
      const response = await fetch(`${this.apiBaseUrl}/api/courses/${id}`, {
        headers: {
          'Content-Type': 'application/json',
          ...(token ? { Authorization: `Bearer ${token}` } : {}),
        },
        cache: 'no-store'
      });

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

      const apiCourse: ApiCourse = await response.json();
      return this.transformApiCourseToCourse(apiCourse);
    } catch (error) {
      console.error(`Error fetching course ${id}:`, error);
      return null;
    }
  }

  async submitApplication(applicationData: CourseApplicationData): Promise<boolean> {
    try {
      const response = await fetch(`${this.apiBaseUrl}/api/course-applications`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(applicationData),
      });
      
      return response.ok;
    } catch (error) {
      console.error('Error submitting application:', error);
      return false;
    }
  }

  private transformApiCoursesToCourses(apiCourses: ApiCourse[]): Course[] {
    return apiCourses.map(apiCourse => this.transformApiCourseToCourse(apiCourse));
  }

  private transformApiCourseToCourse(apiCourse: ApiCourse): Course {
    return {
      id: apiCourse.id.toString(),
      title: apiCourse.title,
      description: apiCourse.description,
      duration: apiCourse.duration,
      seats: apiCourse.seats,
      category: apiCourse.category,
      level: apiCourse.level,
      instructor: apiCourse.instructor,
      price: apiCourse.price || 'N/A',
      startDate: apiCourse.startDate || '',
      image: this.getFullImageUrl(apiCourse.imageUrl),
      eligibility: apiCourse.eligibility || [],
      objectives: apiCourse.objectives || []
    };
  }

  private getRandomDefaultImage(): string {
    const defaultImages = [
      "https://images.unsplash.com/photo-1576091160550-2173dba999ef?w=400&h=200&fit=crop&crop=center",
      "https://images.unsplash.com/photo-1559757175-0eb30cd8c063?w=400&h=300&fit=crop&crop=center",
      "https://images.unsplash.com/photo-1573496359142-b8d87734a5a2?w=400&h=300&fit=crop&crop=center",
      "https://images.unsplash.com/photo-1582750433449-648ed127bb54?w=400&h=300&fit=crop&crop=center",
      "https://images.unsplash.com/photo-1551601651-2a8555f1a136?w=400&h=300&fit=crop&crop=center",
      "https://images.unsplash.com/photo-1559757148-5c350d0d3c56?w=400&h=300&fit=crop&crop=center"
    ];
    return defaultImages[Math.floor(Math.random() * defaultImages.length)];
  }
}

export const educationService = new EducationService();