package com.rit.ems.controller;

import com.rit.ems.model.Note;
import com.rit.ems.repository.NoteRepository;
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.Random;

@RestController
@RequestMapping("/api/notes")
public class NoteController {

    @Autowired
    private NoteRepository noteRepository;

    @GetMapping
    public List<Note> getAllNotes() {
        List<Note> list = noteRepository.findAll();
        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<?> createNote(@RequestBody Note note) {
        if (note.getId() == null) {
            note.setId(System.currentTimeMillis() + new Random().nextInt(1000));
        }
        note.setCreatedAt(Instant.now().toString());
        noteRepository.save(note);
        return ResponseEntity.ok(note);
    }
}
