using BITKit;
using IDIS;
using IDIS.Models;
using IDIS.Services;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;

namespace IDIS_Server_SIM.Controllers;

[ApiController]

public class IDIS_TemplateController:Controller
{
    private readonly IDIS_TemplateService _service;
    private readonly ILogger<IDIS_TemplateController> _logger;

    public IDIS_TemplateController(IDIS_TemplateService service, ILogger<IDIS_TemplateController> logger)
    {
        _service = service;
        _logger = logger;
    }

    [Route("/snms/api/template/v1")]
    [HttpGet]
    public async Task<IActionResult> Query(string prefix, string version)
    {
        try
        {
            return Ok(new IDIS_Response(await _service.QueryAsync(prefix, version)));
        }
        catch (Exception e)
        {
            return BadRequest(new IDIS_Response(e.Message,false)
            {
                Status = 2
            });
        }
    }

    [Route("/snms/api/template/v1")]
    [HttpPost]
    public async Task<IActionResult> Save()
    {
        using var reader = new StreamReader(Request.Body);
        var json = await reader.ReadToEndAsync();

        try
        {
            var data = JsonConvert.DeserializeObject<IDIS_Template>(json)!;
            await _service.SaveAsync(data);
            return Ok(new IDIS_Response());
        }
        catch (Exception e)
        {
            return BadRequest(new IDIS_Response(e.Message, false)
            {
                Status = 2
            });
        }
    }
}