import { api } from './api';
import { Course } from '../types/schedule';

interface ScheduleCourseDTO {
  id: string;
  name: string;
  teacher?: string;
  location?: string;
  day_of_week: number;
  start_section: number;
  end_section: number;
  weeks: number[];
  color?: string;
}

interface ScheduleCourseListResponse {
  list: ScheduleCourseDTO[];
}

interface CreateScheduleCourseRequest {
  name: string;
  teacher?: string;
  location?: string;
  day_of_week: number;
  start_section: number;
  end_section: number;
  weeks: number[];
  color?: string;
}

interface CreateScheduleCourseResponse {
  course: ScheduleCourseDTO;
}

interface SyncScheduleRequest {
  username: string;
  password: string;
  semester?: string;
}

interface SyncScheduleResponse {
  success: boolean;
  message: string;
  synced_count: number;
  error_message?: string;
}

const toCourse = (dto: ScheduleCourseDTO): Course => ({
  id: dto.id,
  name: dto.name,
  teacher: dto.teacher,
  location: dto.location,
  dayOfWeek: dto.day_of_week,
  startSection: dto.start_section,
  endSection: dto.end_section,
  weeks: dto.weeks ?? [],
  color: dto.color,
});

class ScheduleService {
  async getCourses(week?: number): Promise<Course[]> {
    const params = week ? { week } : undefined;
    const response = await api.get<ScheduleCourseListResponse>('/schedule/courses', params);
    return response.data.list.map(toCourse);
  }

  async createCourse(input: CreateScheduleCourseRequest): Promise<Course> {
    const response = await api.post<CreateScheduleCourseResponse>('/schedule/courses', input);
    return toCourse(response.data.course);
  }

  async updateCourse(courseId: string, input: CreateScheduleCourseRequest): Promise<Course> {
    const response = await api.put<CreateScheduleCourseResponse>(`/schedule/courses/${courseId}`, input);
    return toCourse(response.data.course);
  }

  async deleteCourse(courseId: string): Promise<void> {
    await api.delete(`/schedule/courses/${courseId}`);
  }

  async syncSchedule(req: SyncScheduleRequest): Promise<SyncScheduleResponse> {
    const response = await api.post<SyncScheduleResponse>('/schedule/sync', req);
    return response.data;
  }
}

export const scheduleService = new ScheduleService();
export type { CreateScheduleCourseRequest, SyncScheduleRequest };
