using Hcs.WebApp.Data.Hcs;
using Hcs.WebApp.Services;
using Hcs.WebApp.Utils;

namespace Hcs.WebApp.BackgroundServices.CampaignManagers
{
    public abstract class ManagerBase(
        IServiceScopeFactory scopeFactory,
        OperationExecutionState operationExecutionState,
        ResultWaitState resultWaitState,
        Campaign campaign) : IManager
    {
        protected readonly IServiceScope scope = scopeFactory.CreateScope();
        protected readonly OperationExecutionState operationExecutionState = operationExecutionState;
        protected readonly ResultWaitState resultWaitState = resultWaitState;
        protected readonly Campaign campaign = campaign;

        private HeadquartersService? headquartersService;

        protected HeadquartersService HeadquartersService => headquartersService ??= scope.ServiceProvider.GetRequiredService<HeadquartersService>();

        public Campaign Campaign => campaign;

        public IManager.ManagerState State { get; protected set; } = IManager.ManagerState.Created;

        public abstract Task ProcessAsync();

        public async Task EndWithFailAsync(Exception e)
        {
            await HeadquartersService.SetCampaignEndedWithFailAsync(campaign.Id, e.CombineMessages());

            State = IManager.ManagerState.Ended;
        }
    }
}
