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> GetMineAsync(Guid userId) { var templates = await _repo.GetByUserIdAsync(userId); return templates.Select(MapToDto); } public async Task 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 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 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 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 }; } }