import dayjs, { type Dayjs } from 'dayjs';

export interface ScheduleFormValues {
  classId: number;
  classroomId: number;
  weekDay: number;
  subject: string;
  teacherId?: number;
  notes?: string;
  attendanceAdvanceMinutes: number;
  timeRange: [Dayjs, Dayjs];
  dateRange: [Dayjs, Dayjs];
}

export interface EditableSchedule {
  id?: number;
  classId: number;
  classroomId: number;
  weekDay: number;
  subject: string;
  teacherId: number | null;
  notes?: string | null;
  attendanceAdvanceMinutes?: number | null;
  startTime: string;
  endTime: string;
  startDate: string;
  endDate: string;
}

export const scheduleToFormValues = (schedule: EditableSchedule): ScheduleFormValues => ({
  classId: schedule.classId,
  classroomId: schedule.classroomId,
  weekDay: schedule.weekDay,
  subject: schedule.subject,
  teacherId: schedule.teacherId ?? undefined,
  notes: schedule.notes ?? undefined,
  attendanceAdvanceMinutes: schedule.attendanceAdvanceMinutes ?? 30,
  timeRange: [dayjs(`2000-01-01 ${schedule.startTime}`), dayjs(`2000-01-01 ${schedule.endTime}`)],
  dateRange: [dayjs(schedule.startDate), dayjs(schedule.endDate)],
});

export const buildSchedulePayload = (values: ScheduleFormValues) => ({
  classId: values.classId,
  classroomId: values.classroomId,
  weekDay: values.weekDay,
  subject: values.subject,
  teacherId: values.teacherId,
  notes: values.notes?.trim() || undefined,
  attendanceAdvanceMinutes: values.attendanceAdvanceMinutes,
  startTime: values.timeRange[0].format('HH:mm'),
  endTime: values.timeRange[1].format('HH:mm'),
  startDate: values.dateRange[0].format('YYYY-MM-DD'),
  endDate: values.dateRange[1].format('YYYY-MM-DD'),
});
