package com.rit.ems.controller;

import com.rit.ems.model.ClassMapping;
import com.rit.ems.repository.ClassMappingRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Random;

@RestController
@RequestMapping("/api/classes")
public class ClassController {

    @Autowired
    private ClassMappingRepository classMappingRepository;

    @GetMapping
    public List<ClassMapping> getAllClasses() {
        return classMappingRepository.findAll();
    }

    @PostMapping
    public ResponseEntity<?> createClass(@RequestBody ClassMapping classMapping) {
        if (classMapping.getId() == null) {
            classMapping.setId(System.currentTimeMillis() + new Random().nextInt(1000));
        }
        if (classMapping.getStatus() == null) {
            classMapping.setStatus("Ready");
        }
        classMappingRepository.save(classMapping);
        return ResponseEntity.ok(classMapping);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteClass(@PathVariable Long id) {
        classMappingRepository.deleteById(id);
        return ResponseEntity.ok(Map.of("message", "Class mapping deleted successfully"));
    }

    @PostMapping("/promote")
    public ResponseEntity<?> promoteClasses(@RequestParam String institution) {
        List<ClassMapping> classes = classMappingRepository.findAll();
        for (ClassMapping cm : classes) {
            if (cm.getInstitution() != null && cm.getInstitution().trim().equalsIgnoreCase(institution.trim())) {
                switch (cm.getAcademicYear()) {
                    case "1st Year":
                        cm.setAcademicYear("2nd Year");
                        classMappingRepository.save(cm);
                        break;
                    case "2nd Year":
                        cm.setAcademicYear("3rd Year");
                        classMappingRepository.save(cm);
                        break;
                    case "3rd Year":
                        cm.setAcademicYear("4th Year");
                        classMappingRepository.save(cm);
                        break;
                    case "4th Year":
                        classMappingRepository.delete(cm);
                        break;
                }
            }
        }
        return ResponseEntity.ok(Map.of("message", "Academic year promotion completed for " + institution));
    }
}
