using Fast.Web.Models;
using Microsoft.AspNetCore.OData.Routing.Controllers;

namespace Fast.Web.Controllers;

[Authorize]
[ApiController]
[Route("api/[controller]")]
public class ActualsGasHistoryController(MyDbContext context) : ODataController
{
    private readonly MyDbContext db = context;
    private readonly AuthorizationHelper authHelper = new(Main.IsAuthenticationEnabled);

    [Permission("Actuals Gas", PermissionType.View)]
    [Route("[action]")]
    public async Task<IActionResult> GetRequiredData()
    {
        var hasModifyPermission = await authHelper.IsAuthorizedAsync(User, "Actuals Gas", PermissionType.Modify);
        var result = new { hasModifyPermission };
        return Ok(result);
    }

    [Permission("Actuals Gas", PermissionType.View)]
    [Route("[action]")]
    public async Task<IActionResult> GetHistoryItems(int actualTypeId, int supplyNomId, int marketNomId, int? lastTransferId)
    {
        var historyItems = await (
            from q in db.GasActuals
            where q.ActualTypeId == actualTypeId && q.SupplyNomId == supplyNomId && q.MarketNomId == marketNomId && q.LastTransferId == lastTransferId
            orderby q.SaveDate descending
            select new ActualsGasListItem
            {
                SupplyNomId = q.SupplyNomId,
                MarketNomId = q.MarketNomId,
                LastTransferId = lastTransferId,
                Price = q.Price,
                PriceAdj = q.Adder,
                TransportRate = q.TransportRate,
                ActualVolume = q.Volume,
                IsLinked = q.IsLinked,
                SaveDate = q.SaveDate
            }
        ).ToListAsync();

        return Ok(historyItems);
    }

    [Permission("Actuals Gas", PermissionType.Modify)]
    [Route("[action]")]
    public async Task<IActionResult> SaveHistoryItems(int actualTypeId, int supplyNomId, int marketNomId, int? lastTransferId, ActualsGasListItem[] itemsToSave)
    {
        await db.Database.CreateExecutionStrategy().ExecuteAsync(async () =>
        {
            using var dbContextTransaction = await db.Database.BeginTransactionAsync();
            db.GasActuals.RemoveRange(db.GasActuals.Where(x => x.ActualTypeId == actualTypeId && x.SupplyNomId == supplyNomId && x.MarketNomId == marketNomId && x.LastTransferId == lastTransferId));
            var appUserId = Util.GetAppUserId(User);
            foreach (var item in itemsToSave)
            {
                var itemHasAnyValues =
                    item.ActualVolume.HasValue
                    || item.Price.HasValue
                    || item.PriceAdj.HasValue
                    || item.TransportRate.HasValue;

                if (itemHasAnyValues)
                {
                    GasActual dbItem = new();
                    dbItem.ActualTypeId = actualTypeId;
                    dbItem.SupplyNomId = item.SupplyNomId;
                    dbItem.MarketNomId = item.MarketNomId;
                    dbItem.LastTransferId = item.LastTransferId;
                    dbItem.Volume = item.ActualVolume;
                    dbItem.Price = item.Price;
                    dbItem.Adder = item.PriceAdj;
                    dbItem.TransportRate = item.TransportRate;
                    dbItem.IsLinked = item.IsLinked;
                    dbItem.SaveDate = item.SaveDate;
                    dbItem.SavedBy = appUserId;
                    db.GasActuals.Add(dbItem);
                }
            }
            await db.SaveChangesAsync();
            await dbContextTransaction.CommitAsync();
        });
        return Ok();
    }
}
