using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Play.Catalog.Service.Dtos;
using Play.Catalog.Service.Repositories;

namespace Play.Catalog.Service.Controllers;

[ApiController]
[Route("items")]
public class ItemsContoller : ControllerBase
{

    private readonly ItemsRepository itemsRepository = new();

    public static readonly List<ItemDto> items = new(){
        new ItemDto(Guid.NewGuid(), "Potion", "Heals HP.", 50, DateTimeOffset.UtcNow),
        new ItemDto(Guid.NewGuid(), "Antidote", "Cures poison.", 75, DateTimeOffset.UtcNow),
        new ItemDto(Guid.NewGuid(), "Sword", "Good quality sword.", 200, DateTimeOffset.UtcNow)
    };

    [HttpGet]
    public IEnumerable<ItemDto> Get()
    {
        return items;
    }
    
    [HttpGet("{id}")]
    public ActionResult<ItemDto> GetById(Guid id)
    {
        var item = items.Where(item => item.Id == id).SingleOrDefault();
        if (item == null) return NotFound();
        return item;
    }

    [HttpPost]
    public ActionResult<ItemDto> Post(CreateItemDto createItemDto)
    {
        var item = new ItemDto(
            Guid.NewGuid(), 
            createItemDto.Name, 
            (createItemDto.Description!=null) ? createItemDto.Description:"", 
            createItemDto.Price, 
            DateTimeOffset.UtcNow
        );
        items.Add(item);
        return CreatedAtAction(nameof(GetById), new {Id = item.Id}, item);
    }    

    [HttpPut("{id}")]
    public IActionResult Put(Guid id, UpdateItemDto updateItemDto)
    {
        var existingItem = items.Where(item => item.Id == id).SingleOrDefault();
        if (existingItem == null) 
            return NotFound();
        var updatedItem = existingItem with {
            Name = (updateItemDto.Name != null) ? updateItemDto.Name : existingItem.Name,
            Description = (updateItemDto.Description != null) ? updateItemDto.Description : existingItem.Description,
            Price = updateItemDto.Price
        };

        var index = items.FindIndex(item => item.Id == id);
        items[index] = updatedItem;

        return NoContent();
    }

    [HttpDelete("{id}")]
    public IActionResult Delete(Guid id)
    {

        var index = items.FindIndex(item => item.Id == id);
        if (index < 0) 
            return NotFound();
        items.RemoveAt(index);

        return NoContent();
    }
}