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

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

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

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

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

            itemsQueryable = (
                from q in db.ForceMajeures
                select new ForceMajeureListItem
                {
                    ForceMajeureId = q.Id,
                    Label = q.Label,
                    Language = q.Language ?? ""
                }
            ).AsNoTracking();

            return itemsQueryable;
        }

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

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

        [Permission("Force Majeure", PermissionType.View)]
        [Route("[action]")]
        public async Task<IActionResult> GetDetail(int id)
        {
            var detail = await (
                from q in db.ForceMajeures
                where q.Id == id
                select new ForceMajeureDetail
                {
                    ForceMajeureId = q.Id,
                    LabelName = q.Label,
                    Language = q.Language ?? ""
                }
            ).AsNoTracking().FirstAsync();

            return Ok(detail);
        }

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

        [Permission("Force Majeure", PermissionType.Modify)]
        [Route("[action]")]
        public async Task<IActionResult> SaveDetail(ForceMajeureDetail detail, SaveType saveType)
        {
            int resultId = 0;
            await db.Database.CreateExecutionStrategy().Execute(async () =>
            {
                using var dbContextTransaction = await db.Database.BeginTransactionAsync();
                ForceMajeure? dbItem = null;
                if (saveType != SaveType.New)
                {
                    dbItem = await (
                        from q in db.ForceMajeures
                        where q.Id == detail.ForceMajeureId
                        select q
                    ).FirstOrDefaultAsync();
                }

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

                var d = detail;
                dbItem.Label = d.LabelName;
                dbItem.Language = d.Language;

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

                await dbContextTransaction.CommitAsync();
            });

            return Ok(resultId);
        }

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

            return Ok();
        }
    }
}
