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);
            return;
        }

        if (targets.Any(t => t.Id == currentUserId))
        {
            await SendErrorsAsync(400, ct);
            return;
        }

        int totalMembers = targets.Count + 1;

        // 1. Créer le groupe SANS DiscussionId pour l'instant
        Models.Group group = new()
        {
            Name = req.GroupName,
            MembersAmount = totalMembers,
            DiscussionId = 0, // temporaire
            GroupUsers = targets
                .Select(t => new GroupUser { UserId = t.Id })
                .Append(new GroupUser { UserId = currentUserId })
                .ToList()
        };

        db.Groups.Add(group);
        await db.SaveChangesAsync(ct); // group.Id disponible

        // 2. Créer la discussion avec le GroupId
        Models.Discussion discussion = new()
        {
            IsGroup = true,
            GroupId = group.Id,
            UserDiscussions = targets
                .Select(t => new UserDiscussion { UserId = t.Id })
                .Append(new UserDiscussion { UserId = currentUserId })
                .ToList()
        };

        db.Discussions.Add(discussion);
        await db.SaveChangesAsync(ct); // discussion.Id disponible

        // 3. Mettre à jour le DiscussionId sur le groupe
        group.DiscussionId = discussion.Id;
        await db.SaveChangesAsync(ct);

        await SendOkAsync(new GetDiscussionDto
        {
            Id = discussion.Id,
            IsGroup = true,
            Name = group.Name,
            MembersCount = totalMembers
        }, ct);
    }
}

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