using BookHive.DTO.Member;
using BookHive.Models;
using BookHive.Repositories;
using BookHive.Specifications.Members;
using FastEndpoints;

namespace BookHive.Endpoints.Members;

public class UpdateMemberEndpoint(MemberRepository memberRepository, AutoMapper.IMapper mapper) : Endpoint<UpdateMemberDto>
{
    public override void Configure()
    {
        Put("/members/{@Id}/", x => new { x.Id });
        AllowAnonymous();
    }

    public override async Task HandleAsync(UpdateMemberDto req, CancellationToken ct)
    {
        Member? member = await memberRepository.SingleOrDefaultAsync(new GetMemberByIdSpec(req.Id), ct);
        if (member is null)
        {
            await Send.NotFoundAsync(ct);
            return;
        }

        mapper.Map(req, member);
        await memberRepository.SaveChangesAsync(ct);
        await Send.NoContentAsync(ct);
    }
}