using System.Transactions;
using Microsoft.AspNetCore.Mvc;
using UnivateProperties_API.Containers.Users;
using UnivateProperties_API.Helpers;
using UnivateProperties_API.Model.Users;
using UnivateProperties_API.Repository;

namespace User_API.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class AgentController : ControllerBase
    {
        private readonly IRepository<Agent> _Repo;

        public AgentController(IRepository<Agent> repo)
        {
            _Repo = repo;
        }

        [HttpGet]
        public IActionResult Get()
        {
            return new OkObjectResult(_Repo.GetAll());
        }

        [HttpGet("{id}")]
        public IActionResult Get(int id)
        {
            return new OkObjectResult(_Repo.Get(x => x.Id == id));
        }

        [HttpPost()]
        public IActionResult Post([FromBody] AgentDto agentDto)
        {
            using (var scope = new TransactionScope())
            {
                Agent agent = agentDto.Agent;
                MyCommon.CreatePasswordHash(agentDto.Password, out byte[] passwordHash, out byte[] passwordSalt);

                agent.User.PasswordHash = passwordHash;
                agent.User.PasswordSalt = passwordSalt;
                _Repo.Insert(agent);
                scope.Complete();
                return CreatedAtAction(nameof(Get), new { id = agentDto.Agent.Id }, agentDto.Agent);
            }
        }

        [HttpPut()]
        public IActionResult Put([FromBody] Agent agent)
        {
            if (agent != null)
            {
                using (var scope = new TransactionScope())
                {
                    _Repo.Update(agent);
                    scope.Complete();
                    return new OkResult();
                }
            }
            return new NoContentResult();
        }

        [HttpDelete("{id}")]
        public IActionResult Delete(int id)
        {
            _Repo.RemoveAtId(id);
            return new OkResult();
        }
    }
}