File size: 5,085 Bytes
6d07d79
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
using FlowAPI.Application.DTOs.Template;
using FlowAPI.Application.Interfaces;
using FlowAPI.Domain.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;

namespace FlowAPI.Application.Services
{
    public class TemplateService : ITemplateService
    {
        private const int MaxContentLength = 1_500_000;
        private const int MaxTitleLength = 80;
        private const int MaxDescriptionLength = 300;

        private readonly ICustomTemplateRepository _repo;
        private readonly IUserRepository _userRepo;

        public TemplateService(ICustomTemplateRepository repo, IUserRepository userRepo)
        {
            _repo = repo;
            _userRepo = userRepo;
        }

        public async Task<IEnumerable<TemplateDto>> GetMineAsync(Guid userId)
        {
            var templates = await _repo.GetByUserIdAsync(userId);
            return templates.Select(MapToDto);
        }

        public async Task<TemplateDto?> GetAsync(Guid id, Guid userId)
        {
            var template = await _repo.GetByIdAsync(id);
            if (template is null || template.UserId != userId) return null;
            return MapToDto(template);
        }

        public async Task<TemplateDto> CreateAsync(CreateTemplateDto dto, Guid userId)
        {
            var user = await _userRepo.GetByIdAsync(userId) ?? throw new InvalidOperationException("User not found.");

            if (!Plans.IsPlus(user) && await _repo.CountByUserIdAsync(userId) >= Plans.FreeMaxTemplates)
            {
                throw new InvalidOperationException($"Free plan allows up to {Plans.FreeMaxTemplates} saved templates. Upgrade to Plus for unlimited templates.");
            }

            var title = (dto.Title ?? string.Empty).Trim();
            if (title.Length == 0) throw new InvalidOperationException("Template title is required.");
            if (title.Length > MaxTitleLength) title = title[..MaxTitleLength];

            ValidateContent(dto.Content);

            var template = new CustomTemplate
            {
                Id = Guid.NewGuid(),
                UserId = userId,
                Title = title,
                Description = Truncate(dto.Description, MaxDescriptionLength),
                Category = string.IsNullOrWhiteSpace(dto.Category) ? "Мої" : dto.Category.Trim(),
                Icon = string.IsNullOrWhiteSpace(dto.Icon) ? "LayoutTemplate" : dto.Icon.Trim(),
                ContentJson = dto.Content,
                CreatedAt = DateTime.UtcNow
            };

            return MapToDto(await _repo.CreateAsync(template));
        }

        public async Task<TemplateDto?> UpdateAsync(Guid id, UpdateTemplateDto dto, Guid userId)
        {
            var template = await _repo.GetByIdAsync(id);
            if (template is null || template.UserId != userId) return null;

            if (!string.IsNullOrWhiteSpace(dto.Title)) template.Title = Truncate(dto.Title, MaxTitleLength);
            if (dto.Description != null) template.Description = Truncate(dto.Description, MaxDescriptionLength);
            if (!string.IsNullOrWhiteSpace(dto.Category)) template.Category = dto.Category.Trim();
            if (!string.IsNullOrWhiteSpace(dto.Icon)) template.Icon = dto.Icon.Trim();

            return MapToDto(await _repo.UpdateAsync(template));
        }

        public async Task<bool> DeleteAsync(Guid id, Guid userId)
        {
            var template = await _repo.GetByIdAsync(id);
            if (template is null || template.UserId != userId) return false;
            return await _repo.DeleteAsync(id);
        }

        private static void ValidateContent(string content)
        {
            if (string.IsNullOrWhiteSpace(content)) throw new InvalidOperationException("Template content is empty.");
            if (content.Length > MaxContentLength) throw new InvalidOperationException("Template is too large. Remove images and try again.");

            try
            {
                using var doc = JsonDocument.Parse(content);
                if (!doc.RootElement.TryGetProperty("nodes", out var nodes) || nodes.ValueKind != JsonValueKind.Array || nodes.GetArrayLength() == 0)
                {
                    throw new InvalidOperationException("Template must contain at least one node.");
                }
            }
            catch (JsonException)
            {
                throw new InvalidOperationException("Template content is not valid JSON.");
            }
        }

        private static string Truncate(string? value, int max)
        {
            var trimmed = (value ?? string.Empty).Trim();
            return trimmed.Length > max ? trimmed[..max] : trimmed;
        }

        private static TemplateDto MapToDto(CustomTemplate t) => new()
        {
            Id = t.Id,
            Title = t.Title,
            Description = t.Description,
            Category = t.Category,
            Icon = t.Icon,
            Content = t.ContentJson,
            CreatedAt = t.CreatedAt
        };
    }
}