package com.rit.ems.controller;

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

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

@RestController
@RequestMapping("/api/special-events")
public class SpecialEventController {

    @Autowired
    private SpecialEventRepository specialEventRepository;

    @GetMapping
    public List<SpecialEvent> getAllSpecialEvents() {
        List<SpecialEvent> list = specialEventRepository.findAll();
        for (SpecialEvent se : list) {
            if (se.getStartDate() != null) {
                String sd = se.getStartDate().replace(" ", "T");
                if (!sd.endsWith("Z")) sd += "Z";
                se.setStartDate(sd);
            }
            if (se.getEndDate() != null) {
                String ed = se.getEndDate().replace(" ", "T");
                if (!ed.endsWith("Z")) ed += "Z";
                se.setEndDate(ed);
            }
            if (se.getCreatedAt() != null) {
                String ca = se.getCreatedAt().replace(" ", "T");
                if (!ca.endsWith("Z")) ca += "Z";
                se.setCreatedAt(ca);
            }
        }
        list.sort((a, b) -> {
            String ca = a.getCreatedAt() != null ? a.getCreatedAt() : "";
            String cb = b.getCreatedAt() != null ? b.getCreatedAt() : "";
            return cb.compareTo(ca); // Descending order
        });
        return list;
    }

    @PostMapping
    public ResponseEntity<?> createSpecialEvent(@RequestBody SpecialEvent se) {
        if (se.getId() == null) {
            se.setId(String.valueOf(System.currentTimeMillis() + new Random().nextInt(1000)));
        }
        if (se.getCreatedAt() == null) {
            se.setCreatedAt(Instant.now().toString());
        }
        if (se.getIsActive() == null) {
            se.setIsActive(true);
        }
        if (se.getVerificationStatus() == null) {
            se.setVerificationStatus("APPROVED");
        }
        specialEventRepository.save(se);
        return ResponseEntity.ok(se);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteSpecialEvent(@PathVariable String id) {
        specialEventRepository.deleteById(id);
        return ResponseEntity.ok(Map.of("message", "Special event deleted successfully"));
    }
}
