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

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

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

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

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

            itemsQueryable = (
                from q in db.Books
                select new BookListItem
                {
                    BookId = q.Id,
                    Active = q.IsActive ? "yes" : "no",
                    Book = q.Name ?? ""
                }
            ).AsNoTracking();

            return itemsQueryable;
        }

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

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

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

            return Ok(detail);
        }

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

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

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

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

                var d = detail;
                dbItem.Name = d.BookName;
                dbItem.IsActive = d.IsActive;
                await db.SaveChangesAsync();
                resultId = dbItem.Id;

                await dbContextTransaction.CommitAsync();
            });

            return Ok(resultId);
        }

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

            return Ok();
        }
    }
}
