package com.rit.ems.controller;

import com.rit.ems.model.Announcement;
import com.rit.ems.repository.AnnouncementRepository;
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/announcements")
public class AnnouncementController {

    @Autowired
    private AnnouncementRepository announcementRepository;

    @GetMapping
    public List<Announcement> getAllAnnouncements() {
        List<Announcement> list = announcementRepository.findAll();
        list.sort((a, b) -> {
            String ta = a.getTimestamp() != null ? a.getTimestamp() : "";
            String tb = b.getTimestamp() != null ? b.getTimestamp() : "";
            return tb.compareTo(ta); // Descending order
        });
        return list;
    }

    @PostMapping
    public ResponseEntity<?> createAnnouncement(@RequestBody Announcement ann) {
        if (ann.getId() == null) {
            ann.setId(String.valueOf(System.currentTimeMillis() + new Random().nextInt(1000)));
        }
        ann.setTimestamp(Instant.now().toString());
        announcementRepository.save(ann);
        return ResponseEntity.ok(ann);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteAnnouncement(@PathVariable String id) {
        announcementRepository.deleteById(id);
        return ResponseEntity.ok(Map.of("message", "Announcement deleted successfully"));
    }
}
