using System.Security.Claims;
using FastEndpoints;
using Knots.DTO.Message;
using Knots.DTO.User;
using Microsoft.EntityFrameworkCore;

namespace Knots.Endpoints.Message;

public class GetMessageEndpoint(KnotsDbContext db, AutoMapper.IMapper mapper) : Endpoint<GetDiscussionMessagesRequest, List<GetMessageDetailsDto>>
{
    public override void Configure()
    { 
        Get("/discussions/{DiscussionId}/messages");
        AllowAnonymous();
    }

    public override async Task HandleAsync(GetDiscussionMessagesRequest req, CancellationToken ct)
    {
        int userId = int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);

        // l'utilisateur participe-t-il à cette discussion (privée ou via le groupe) ?
        bool autorise = await db.Discussions
            .Where(d => d.Id == req.DiscussionId)
            .AnyAsync(d =>
                d.UserDiscussions.Any(ud => ud.UserId == userId) ||
                (d.Group != null && d.Group.GroupUsers.Any(gu => gu.UserId == userId)), ct);

        if (!autorise)
        {
            await SendForbiddenAsync(ct);
            return;
        }

        List<GetMessageDetailsDto> messages = await db.Messages
            .Where(m => m.DiscussionId == req.DiscussionId)
            .OrderBy(m => m.Date)
            .Select(m => new GetMessageDetailsDto
            {
                Id = m.Id,
                Contenu = m.Contenu!,
                Date = m.Date,
                AuthorId = m.UserId,
                AuthorName = m.User.Username!
            })
            .ToListAsync(ct);

        await SendOkAsync(messages, ct);
    }
}

public class GetDiscussionMessagesRequest
{
    public int DiscussionId { get; set; }
}