using Application.Abstractions.Data;
using Application.Abstractions.Messaging;

namespace Application.Features.Api.Note.SendNote;

internal sealed class Handler(IAppDbContext db) : ICommandHandler<Command, Response>
{
    public async Task<Response> Handle(Command r, CancellationToken ct)
    {
        if (string.IsNullOrWhiteSpace(r.Title) || string.IsNullOrWhiteSpace(r.Content))
        {
            throw new InvalidOperationException("제목과 내용을 입력해주세요.");
        }

        var note = r.IsSystem
            ? Domain.Entities.Notes.Note.CreateSystem(r.ReceiverMemberID, r.Title, r.Content, r.RelatedType, r.RelatedID)
            : Domain.Entities.Notes.Note.Create(r.SenderMemberID, r.ReceiverMemberID, r.Title, r.Content, false, r.RelatedType, r.RelatedID);

        db.Note.Add(note);
        await db.SaveChangesAsync(ct);

        return new Response(note.ID);
    }
}