using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using noteApi.Data;
using noteApi.Dtos.Note;
using noteApi.Interfaces;

namespace noteApi.Controllers
{
    [Route("api/note")]
    [ApiController]
    public class NoteController : ControllerBase
    {
        private readonly INoteRepository _noteRepo;
        public NoteController(INoteRepository noteRepository)
        {
            _noteRepo = noteRepository;
        }

        [HttpGet]
        public async Task<IActionResult> GetAll()
        {
            var notes = await _noteRepo.GetAllAsync();

            return Ok(notes);
        }

        [HttpGet("{id}")]
        public async Task<IActionResult> GetById([FromRoute] int id)
        {
            var note = await _noteRepo.GetByIdAsync(id);

            if(note == null)
            {
                return NotFound();
            }

            return Ok(note);
        }

        [HttpPost]
        public async Task<IActionResult> Create([FromBody] CreateNoteDto noteDto)
        {
            var note = await _noteRepo.CreateAsync(noteDto);
            return CreatedAtAction(nameof(GetById), new { id = note.Id }, note);
        }

        [HttpPut("{id}")]
        public async Task<IActionResult> Update([FromRoute] int id, [FromBody] CreateNoteDto noteDto)
        {
            var note = await _noteRepo.UpdateAsync(id, noteDto);

            if(note == null)
            {
                return NotFound();
            }

            return Ok(note);
        }

        [HttpDelete("{id}")]
        public async Task<IActionResult> Delete([FromRoute] int id)
        {
            var note = await _noteRepo.DeleteAsync(id);

            if(note == null)
            {
                return NotFound();
            }

            return NoContent();
        }
    }
}
