using Application.Abstractions.Messaging;
﻿using Application.Abstractions.Data;
using Application.Abstractions.Cache;
using SharedKernel.Storage;
using Microsoft.EntityFrameworkCore;

namespace Application.Features.Admin.Document.Create
{
    public sealed class Handler(IAppDbContext db, IEditorImageService editorImage, ICacheService cache) : ICommandHandler<Command>
    {
        public async Task Handle(Command request, CancellationToken ct)
        {
            if (await db.Document.AnyAsync(c => c.Code == request.Code))
            {
                throw new Exception("이미 등록된 문서입니다.");
            }

            var document = Domain.Entities.Page.Document.Create(
                request.Code,
                request.Subject,
                null,
                request.IsActive
            );

            await db.Document.AddAsync(document, ct);

            int affectedRows = await db.SaveChangesAsync();
            if (affectedRows <= 0)
            {
                throw new Exception("문서 등록 중 오류가 발생했습니다.");
            }

            var path = new FileStoragePath(UploadTarget.Editor, UploadFolder.Document, document.ID);
            var html = await editorImage.UploadAsync(request.Content, path, ct);

            document.SetContent(html);

            await db.SaveChangesAsync();
            await cache.RemoveByPrefixAsync("document:", ct);
        }
    }
}