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

namespace Application.Features.Admin.Document.Update
{
    public sealed class Handler(IAppDbContext db, IEditorImageService editorImage, ICacheService cache) : ICommandHandler<Command>
    {
        public async Task Handle(Command request, CancellationToken ct)
        {
            var document = await db.Document.FirstOrDefaultAsync(c => c.ID == request.ID, ct);
            if (document is null)
            {
                throw new Exception("문서를 찾을 수 없습니다.");
            }

            if (await db.Document.AnyAsync(c => c.Code == request.Code && c.ID != request.ID))
            {
                throw new Exception("이미 등록된 문서입니다.");
            }

            var path = new FileStoragePath(UploadTarget.Editor, UploadFolder.Document, request.ID);

            document.Update(
                request.Code,
                request.Subject,
                await editorImage.UploadAsync(request.Content, path, ct),
                request.IsActive
            );

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

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