using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using IntroWebAPI.Models;

namespace IntroWebAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class SalesOrgController : ControllerBase
    {

        private static List<SalesOrg> salesOrgs = new List<SalesOrg>
            {
                new SalesOrg  { ID = 1, Name = "TestName1", Code = "TestCode1", DateFormat = "dd/mm/yyyy"},
                new SalesOrg  { ID = 2, Name = "TestName2", Code = "TestCode2", DateFormat = "dd/mm/yyyy"},
                new SalesOrg  { ID = 3, Name = "TestName3", Code = "TestCode3", DateFormat = "dd/mm/yyyy"}
            };

        public DataContext _context { get; }

        public SalesOrgController (DataContext context)
        {
            _context = context;
        }

        [HttpGet]
        //public async Task<IActionResult> Get()
        public async Task<ActionResult<List<SalesOrg>>> Get()
        {
            //BadRequest() -> 400
            //NotFound()
            return Ok(salesOrgs);

            //return Ok(await _context.SalesOrgs.ToListAsync());
        }

        [HttpGet("{id}")]
        public async Task<ActionResult<SalesOrg>> Get(int id)
        {
            var salesOrg = salesOrgs.Find(x => x.ID == id);
               
            if (salesOrg == null)
            {
                return BadRequest("SalesOrg not Found.");
            }

            return Ok(salesOrg);
        }


        [HttpPost]
        public async Task<ActionResult<List<SalesOrg>>> AddSalesOrg(SalesOrg salesOrg)
        {
            salesOrgs.Add(salesOrg);
            return Ok(salesOrgs);
        }


        [HttpPut]
        public async Task<ActionResult<List<SalesOrg>>> UpdateSalesOrg(SalesOrg salesOrg)
        {

            var so = salesOrgs.Find(x => x.ID == salesOrg.ID);

            if (so == null)
            {
                return BadRequest("SalesOrg not Found.");
            }

            so.Name = salesOrg.Name;
            so.Code = salesOrg.Code;
            so.DateFormat = salesOrg.DateFormat;

            return Ok(salesOrgs);
        }

        [HttpDelete("{id}")]
        public async Task<ActionResult<List<SalesOrg>>> DeleteSalesOrg(int id)
        {

            var so = salesOrgs.Find(x => x.ID == id);

            if (so == null)
            {
                return BadRequest("SalesOrg not Found.");
            }

            salesOrgs.Remove(so);
            return Ok(so);
        }

    }
}
