namespace Fast.Web.Controllers;

[Authorize]
[ApiController]
[Route("api/[controller]")]
public class PriceIndexPublicationController : ODataController
{
    private readonly MyDbContext db;
    public PriceIndexPublicationController(MyDbContext context)
    {
        db = context;
    }

    [Permission("Price Index", PermissionType.View)]
    [Route("[action]")]
    public IActionResult GetItems()
    {
        var items = (
            from q in db.MarketIndexPublications
            select new
            {
                q.Id,
                q.Name
            }
        ).ToList();

        return Ok(items);
    }

    [Permission("Price Index", PermissionType.View)]
    [Route("[action]/{itemId}")]
    public IActionResult GetItemDetail(int itemId)
    {
        var result = (
            from q in db.MarketIndexPublications
            where q.Id == itemId
            select new
            {
                q.Id,
                q.Name
            }
        ).FirstOrDefault();

        return Ok(result);
    }

    [Permission("Price Index", PermissionType.Modify)]
    [Route("[action]")]
    public IActionResult SaveItem(MarketIndexPublication item)
    {
        MarketIndexPublication itemToSave;

        if (item.Id > 0)
        {
            itemToSave = (
                from q in db.MarketIndexPublications
                where q.Id == item.Id
                select q
            ).First();
        }
        else
        {
            itemToSave = new MarketIndexPublication();
            db.Entry(itemToSave).State = EntityState.Added;
        }

        itemToSave.Name = item.Name;

        int count = db.SaveChanges();

        return Ok(count);
    }

    [Permission("Price Index", PermissionType.Modify)]
    [Route("[action]/{id}")]
    public IActionResult DeleteItem(int id)
    {
        var item = db.MarketIndexPublications.Where(x => x.Id == id).First();
        db.Entry(item).State = EntityState.Deleted;

        db.SaveChanges();

        return Ok();
    }
}
