using FastEndpoints;
using Knots.DTO.Discussion;
using Knots.Models;
using Microsoft.EntityFrameworkCore;
using System.Security.Claims;

namespace Knots.Endpoints.Discussion;

public class CreateGroupDiscussionEndpoint(KnotsDbContext db)
    : Endpoint<CreateGroupDiscussionRequest, GetDiscussionDto>
{
    public override void Configure()
    {
        Post("/discussions/group");
    }

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

        
        if (req.Usernames == null || req.Usernames.Count == 0)
        {
            await SendErrorsAsync(400, ct);
            return;
        }

        
        List<Models.User> targets = await db.Users
            .Where(u => req.Usernames.Contains(u.Username!))
            .ToListAsync(ct);

        if (targets.Count != req.Usernames.Count)
        {
            await SendNotFoundAsync(ct); // un ou plusieurs utilisateurs introuvables
            return;
        }

        if (targets.Any(t => t.Id == currentUserId))
        {
            await SendErrorsAsync(400, ct); // pas de discussion avec soi-même
            return;
        }

        
        List<UserDiscussion> members = targets
            .Select(t => new UserDiscussion { UserId = t.Id })
            .ToList();

        members.Add(new UserDiscussion { UserId = currentUserId });

        Models.Discussion discussion = new()
        {
            IsGroup = true,
            UserDiscussions = members
        };

        db.Discussions.Add(discussion);
        await db.SaveChangesAsync(ct);

        await SendOkAsync(new GetDiscussionDto
        {
            Id = discussion.Id,
            IsGroup = true,
            Name = req.GroupName,
            MembersCount = members.Count
        }, ct);
    }
}

public class CreateGroupDiscussionRequest
{
    public string GroupName { get; set; } = "";
    public List<string> Usernames { get; set; } = [];
}