package com.magistr.app.controller;

import com.magistr.app.config.auth.RequireRoles;
import com.magistr.app.dto.RenderedLessonDto;
import com.magistr.app.dto.SemesterDto;
import com.magistr.app.model.Role;
import com.magistr.app.model.Semester;
import com.magistr.app.repository.SemesterRepository;
import com.magistr.app.service.ScheduleQueryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/schedule")
@RequireRoles({Role.ADMIN, Role.EDUCATION_OFFICE, Role.DEPARTMENT, Role.SCHEDULE_VIEWER, Role.TEACHER, Role.STUDENT})
public class ScheduleController {

    private static final Logger logger = LoggerFactory.getLogger(ScheduleController.class);

    private final ScheduleQueryService scheduleQueryService;
    private final SemesterRepository semesterRepository;

    public ScheduleController(ScheduleQueryService scheduleQueryService,
                              SemesterRepository semesterRepository) {
        this.scheduleQueryService = scheduleQueryService;
        this.semesterRepository = semesterRepository;
    }

    @GetMapping("/semesters")
    public List<SemesterDto> getSemesters() {
        return semesterRepository.findAll().stream()
                .sorted(Comparator.comparing(Semester::getStartDate).reversed())
                .map(this::toSemesterDto)
                .toList();
    }

    @GetMapping
    public ResponseEntity<?> getSchedule(
            @RequestParam(required = false) Long groupId,
            @RequestParam(required = false) Long teacherId,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate
    ) {
        logger.info("Запрос динамического расписания: groupId={}, teacherId={}, startDate={}, endDate={}",
                groupId, teacherId, startDate, endDate);

        if ((groupId == null && teacherId == null) || (groupId != null && teacherId != null)) {
            return ResponseEntity.badRequest()
                    .body(Map.of("message", "Передайте ровно один параметр: groupId или teacherId"));
        }

        return ResponseEntity.ok(scheduleQueryService.search(
                groupId,
                teacherId,
                null,
                null,
                null,
                null,
                null,
                null,
                startDate,
                endDate
        ));
    }

    private SemesterDto toSemesterDto(Semester semester) {
        return new SemesterDto(
                semester.getId(),
                semester.getAcademicYear().getId(),
                semester.getAcademicYear().getTitle(),
                semester.getSemesterType(),
                semester.getStartDate(),
                semester.getEndDate()
        );
    }
}
