namespace Fast.Web.Controllers
{
    [Authorize]
    [ApiController]
    [Route("api/[controller]")]
    public class StrategyController : ODataController
    {
        private readonly MyDbContext db;
        private readonly AuthorizationHelper authHelper;

        public StrategyController(MyDbContext context)
        {
            db = context;
            authHelper = new AuthorizationHelper(Main.IsAuthenticationEnabled);
        }

        [Permission("Strategy", PermissionType.View)]
        [Route("/odata/GetStrategyItems")]
        public IActionResult GetItems(ODataQueryOptions<StrategyListItem> queryOptions, bool isExport)
        {
            queryOptions = Util.GetQueryOptionsWithConvertedDates(queryOptions);
            var itemsQueryable = GetItemsInternal();
            var items = (queryOptions.ApplyTo(itemsQueryable) as IEnumerable<StrategyListItem>)?.ToList();

            if (isExport)
                return File(Util.Excel.GetExportFileStream(items), "application/octet-stream");
            else
                return Ok(items);
        }

        [Permission("Strategy", PermissionType.View)]
        [Route("[action]")]
        public IQueryable<StrategyListItem> GetItemsInternal()
        {
            IQueryable<StrategyListItem>? itemsQueryable = null;

            itemsQueryable = (
                from q in db.Strategies
                select new StrategyListItem
                {
                    StrategyId = q.Id,
                    Active = q.IsActive ? "yes" : "no",
                    Strategy = q.Name ?? ""
                }
            ).AsNoTracking();

            return itemsQueryable;
        }

        [Permission("Strategy", PermissionType.View)]
        [Route("[action]")]
        public async Task<IActionResult> GetRequiredData()
        {
            var hasModifyPermission = await authHelper.IsAuthorizedAsync(User, "Strategy", PermissionType.Modify);

            var result = new { hasModifyPermission };
            return Ok(result);
        }

        [Permission("Strategy", PermissionType.View)]
        [Route("[action]")]
        public async Task<IActionResult> GetDetail(int id)
        {
            var detail = await (
                from q in db.Strategies
                where q.Id == id
                select new StrategyDetail
                {
                    StrategyId = q.Id,
                    StrategyName = q.Name ?? "",
                    IsActive = q.IsActive
                }
            ).AsNoTracking().FirstAsync();

            return Ok(detail);
        }

        public enum SaveType
        {
            New = 1,
            Normal = 2
        }

        [Permission("Strategy", PermissionType.Modify)]
        [Route("[action]")]
        public async Task<IActionResult> SaveDetail(StrategyDetail detail, SaveType saveType)
        {
            int resultId = 0;

            await db.Database.CreateExecutionStrategy().Execute(async () =>
            {
                using var dbContextTransaction = await db.Database.BeginTransactionAsync();
                Strategy? dbItem = null;
                if (saveType != SaveType.New)
                {
                    dbItem = await (
                        from q in db.Strategies
                        where q.Id == detail.StrategyId
                        select q
                    ).FirstOrDefaultAsync();
                }

                if (dbItem == null) //if the item does not exist then add it
                {
                    dbItem = new Strategy();
                    db.Strategies.Add(dbItem);
                }
                else
                {
                    //remove existing items so that they get completely re-inserted
                }

                var d = detail;
                dbItem.Name = d.StrategyName;
                dbItem.IsActive = d.IsActive;

                await db.SaveChangesAsync();
                resultId = dbItem.Id;

                await dbContextTransaction.CommitAsync();
            });

            return Ok(resultId);
        }

        [Permission("Strategy", PermissionType.Modify)]
        [Route("[action]/{id}")]
        public async Task<IActionResult> DeleteDetail(int id)
        {
            Strategy dbItem = await db.Strategies.Where(x => x.Id == id).FirstAsync();
            db.Strategies.Remove(dbItem);
            await db.SaveChangesAsync();

            return Ok();
        }
    }
}
