package com.rit.ems.controller;

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

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

@RestController
@RequestMapping("/api/attendance")
public class AttendanceController {

    @Autowired
    private AttendanceRepository attendanceRepository;

    @GetMapping
    public List<Attendance> getAttendance(@RequestParam(required = false) String registrationId,
                                          @RequestParam(required = false) Long eventId) {
        if (registrationId != null) {
            return attendanceRepository.findByRegistrationId(registrationId);
        }
        if (eventId != null) {
            return attendanceRepository.findByEventId(eventId);
        }
        return attendanceRepository.findAll();
    }

    @PostMapping
    public ResponseEntity<?> saveAttendance(@RequestBody Object payload) {
        List<Map<String, Object>> records = new ArrayList<>();
        if (payload instanceof List) {
            records = (List<Map<String, Object>>) payload;
        } else if (payload instanceof Map) {
            records.add((Map<String, Object>) payload);
        }

        for (Map<String, Object> rec : records) {
            String regId = (String) (rec.containsKey("registrationId") ? rec.get("registrationId") : rec.get("registration_id"));
            String day = (String) (rec.containsKey("dayLabel") ? rec.get("dayLabel") : 
                          (rec.containsKey("day_idx") ? rec.get("day_idx") : "Day 1"));
            String slot = (String) (rec.containsKey("batchLabel") ? rec.get("batchLabel") : 
                           (rec.containsKey("batch_idx") ? rec.get("batch_idx") : "Batch 1"));
            
            Object eventIdObj = rec.containsKey("eventId") ? rec.get("eventId") : rec.get("event_id");
            Long eventId = eventIdObj != null ? Long.parseLong(eventIdObj.toString()) : null;

            String id = regId + "_" + day + "_" + slot;
            Boolean isPresent = (Boolean) (rec.containsKey("isPresent") ? rec.get("isPresent") : rec.get("is_present"));
            String date = (String) rec.get("date");
            if (date == null) {
                date = LocalDate.now().toString();
            }

            Attendance att = new Attendance();
            att.setId(id);
            att.setRegistrationId(regId);
            att.setEventId(eventId);
            att.setDayLabel(day);
            att.setBatchLabel(slot);
            att.setIsPresent(Boolean.TRUE.equals(isPresent));
            att.setDate(date);

            attendanceRepository.save(att);
        }
        return ResponseEntity.ok(Map.of("message", "Attendance updated successfully"));
    }
}
