using CashLineERP.Contracts.Notifications;

namespace CashLineERP.Application.Notifications;

public sealed class NotificationTemplateService : INotificationTemplateService
{
    private readonly INotificationTemplateRepository _repository;

    public NotificationTemplateService(INotificationTemplateRepository repository)
    {
        _repository = repository;
    }

    public IReadOnlyCollection<NotificationTemplateResponse> GetTemplates(bool activeOnly = false, string? channelCode = null) =>
        _repository.GetTemplates(activeOnly, channelCode).Select(Map).ToArray();

    public NotificationTemplateResponse? GetTemplate(long notificationTemplateId)
    {
        var template = _repository.GetTemplate(notificationTemplateId);
        return template is null ? null : Map(template);
    }

    public NotificationTemplateResponse CreateTemplate(CreateNotificationTemplateRequest request) =>
        Map(_repository.Create(new CreateNotificationTemplateCommand(
            request.TemplateName,
            request.ChannelCode,
            request.SubjectTemplate,
            request.BodyTemplate,
            request.Notes)));

    public NotificationTemplateResponse SubmitTemplate(long notificationTemplateId, long actorUserId) =>
        Map(_repository.Submit(notificationTemplateId, actorUserId));

    public NotificationTemplateResponse ApproveTemplate(long notificationTemplateId, long actorUserId) =>
        Map(_repository.Approve(notificationTemplateId, actorUserId));

    public NotificationTemplateResponse ActivateTemplate(long notificationTemplateId, long actorUserId) =>
        Map(_repository.Activate(notificationTemplateId, actorUserId));

    private static NotificationTemplateResponse Map(NotificationTemplateDetailView template) =>
        new(
            template.NotificationTemplateId,
            template.TemplateCode,
            template.TemplateName,
            template.ChannelCode,
            template.SubjectTemplate,
            template.BodyTemplate,
            template.StatusCode,
            template.IsActive,
            template.Notes,
            template.SubmittedAtUtc,
            template.SubmittedByUserId,
            template.ApprovedAtUtc,
            template.ApprovedByUserId,
            template.ActivatedAtUtc,
            template.ActivatedByUserId);
}
