using ErsatzTV.Core; using ErsatzTV.Core.Api.ChannelTemplates; using ErsatzTV.Core.Domain; using ErsatzTV.Core.Interfaces.Repositories; using ErsatzTV.Infrastructure.Data; using Microsoft.EntityFrameworkCore; namespace ErsatzTV.Application.ChannelTemplates; public class CreateChannelTemplateHandler( IDbContextFactory dbContextFactory, IConfigElementRepository configElementRepository) : IRequestHandler> { public async Task> Handle( CreateChannelTemplate request, CancellationToken cancellationToken) { await using TvContext dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken); Option maybeError = await ChannelTemplateCommandBase.ValidateCommon(dbContext, request, null, cancellationToken); foreach (BaseError error in maybeError) { return error; } var template = new ChannelTemplate(); request.ApplyTo(template); await dbContext.ChannelTemplates.AddAsync(template, cancellationToken); await dbContext.SaveChangesAsync(cancellationToken); int? defaultTemplateId = await ChannelTemplateDefault.GetDefaultTemplateId(configElementRepository, cancellationToken); return ChannelTemplateMapper.ProjectToResponseModel(template, defaultTemplateId); } }