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

namespace Knots.Endpoints.User;

public class UpdateUserEndpoint(KnotsDbContext knotsDbContext) : Endpoint <UpdateUserDto, GetUserDetailsDto>
{
    public override void Configure()
    { 
        Put ("/users/{@Id}", x => new { x.Username });
    }

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

        if (databaseUser == null)
        {
            await Send.NotFoundAsync(ct);
            return;
        }
        else
        {
            databaseUser.Username = req.Username;
            databaseUser.Password = req.Password;
            databaseUser.Description = req.Description;
            databaseUser.Tel = req.Tel;
            databaseUser.Email = req.Email;
            databaseUser.ProfilePicture = req.ProfilePicture;
        }
        await knotsDbContext.SaveChangesAsync(ct);
        
        GetUserDetailsDto dto = new()
        {
            Username = databaseUser.Username,
            Password = databaseUser.Password,
            Description = databaseUser.Description,
            Tel = databaseUser.Tel,
            Email = databaseUser.Email,
            ProfilePicture = databaseUser.ProfilePicture
        };
        
        await Send.OkAsync(dto, ct);
    }
}