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

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

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

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

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

            itemsQueryable = (
                from q in db.Portfolios
                select new PortfolioListItem
                {
                    PortfolioId = q.Id,
                    Active = q.IsActive ? "yes" : "no",
                    Portfolio = q.Name ?? ""
                }
            ).AsNoTracking();

            return itemsQueryable;
        }

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

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

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

            return Ok(detail);
        }

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

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

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

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

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

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

                await dbContextTransaction.CommitAsync();
            });

            return Ok(resultId);
        }

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

            return Ok();
        }
    }
}
