using FastEndpoints;
using Knots.DTO.User;
using Microsoft.EntityFrameworkCore;

namespace Knots.Endpoints.User;

public class PatchUserContactEndpoint(KnotsDbContext db, AutoMapper.IMapper mapper) : Endpoint<UpdateUserContactDto>
{
    public override void Configure()
    {
        Patch("/users/{@Id}/contact/", x => new {x.Id});
        AllowAnonymous();
    }

    public override async Task HandleAsync(UpdateUserContactDto req, CancellationToken ct)
    {
        Models.User? databaseUser = await db.Users.SingleOrDefaultAsync(x => x.Id == req.Id, cancellationToken: ct);

        if (databaseUser is null)
        {
            await Send.NotFoundAsync(ct);
            return;
        }

        if (databaseUser.Email != req.Email)
        {
            databaseUser.Email = req.Email;
        }
        else
        {
            databaseUser.Email = databaseUser.Email;
        }

        if (databaseUser.Tel != req.Tel)
        {
            databaseUser.Tel = req.Tel;
        }else
        {
            databaseUser.Tel = databaseUser.Tel;
        }
        
        mapper.Map(req, databaseUser);

        await db.SaveChangesAsync(ct);
        await Send.NoContentAsync(ct);
    }
}