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 GetAllChannelTemplatesHandler(
    IDbContextFactory<TvContext> dbContextFactory,
    IConfigElementRepository configElementRepository)
    : IRequestHandler<GetAllChannelTemplates, List<ChannelTemplateResponseModel>>
{
    public async Task<List<ChannelTemplateResponseModel>> Handle(
        GetAllChannelTemplates request,
        CancellationToken cancellationToken)
    {
        await using TvContext dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);
        int? defaultTemplateId =
            await ChannelTemplateDefault.GetDefaultTemplateId(configElementRepository, cancellationToken);
        return await dbContext.ChannelTemplates
            .AsNoTracking()
            .OrderBy(t => t.IsSystem ? 0 : 1)
            .ThenBy(t => t.Name)
            .Select(t => ChannelTemplateMapper.ProjectToResponseModel(t, defaultTemplateId))
            .ToListAsync(cancellationToken);
    }
}
