using Application.Abstractions.Data;
using Application.Abstractions.Messaging;
using Microsoft.EntityFrameworkCore;

namespace Application.Features.Api.Crew.GenerateInviteCode;

internal sealed class Handler(IAppDbContext db) : ICommandHandler<Command, Response>
{
    public async Task<Response> Handle(Command request, CancellationToken ct)
    {
        var crew = await db.Crew
            .FirstOrDefaultAsync(c => c.ID == request.CrewID, ct);

        if (crew is null)
        {
            throw new KeyNotFoundException("크루를 찾을 수 없습니다.");
        }

        var code = crew.GenerateInviteCode();
        await db.SaveChangesAsync(ct);

        return new Response(code);
    }
}