package ru.mcs.diary.parent;

import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import ru.mcs.diary.auth.CurrentUser;
import ru.mcs.diary.auth.CustomUserDetails;
import ru.mcs.diary.common.exception.ResourceNotFoundException;
import ru.mcs.diary.student.StudentParent;
import ru.mcs.diary.student.StudentParentRepository;

import java.util.List;

@Controller
@RequestMapping("/parent")
@RequiredArgsConstructor
public class ParentDashboardController {

    private final ParentRepository parentRepository;
    private final StudentParentRepository studentParentRepository;

    @GetMapping("/dashboard")
    public String dashboard(@CurrentUser CustomUserDetails user, Model model) {
        Parent parent = parentRepository.findById(user.getParentId())
                .orElseThrow(() -> new ResourceNotFoundException("Родитель", user.getParentId()));

        List<StudentParent> children = studentParentRepository.findAllByParentIdWithStudent(parent.getId());

        model.addAttribute("parent", parent);
        model.addAttribute("children", children);
        model.addAttribute("user", user);

        return "parent/dashboard";
    }

    @GetMapping("/child/{studentId}")
    public String childDetails(@PathVariable Long studentId,
                               @CurrentUser CustomUserDetails user,
                               Model model) {
        Parent parent = parentRepository.findById(user.getParentId())
                .orElseThrow(() -> new ResourceNotFoundException("Родитель", user.getParentId()));

        // Используем новый метод с загрузкой групп
        StudentParent childRelation = studentParentRepository
                .findByParentIdAndStudentIdWithGroups(parent.getId(), studentId)
                .orElseThrow(() -> new IllegalArgumentException("Доступ запрещён"));

        model.addAttribute("parent", parent);
        model.addAttribute("student", childRelation.getStudent());
        model.addAttribute("relation", childRelation);
        model.addAttribute("user", user);

        return "parent/child";
    }

}
