package chat

import (
	"context"

	"juwan-backend/app/chat/chatcore"

	"github.com/wwweww/go-wst/protocol"
)

func (h *Handler) handleCreateGroup(conn protocol.Connection, msg *WsMessage) error {
	uid := h.getUserId(conn)
	if uid <= 0 {
		return conn.SendJSON(context.Background(), WsResponse{
			Type:    "error",
			Content: "authentication required",
		})
	}

	session, err := h.svcCtx.Store.CreateSession(chatcore.SessionTypeGroup, msg.Name, uid, []int64{uid})
	if err != nil {
		return conn.SendJSON(context.Background(), WsResponse{
			Type:    "error",
			Content: err.Error(),
		})
	}

	return conn.SendJSON(context.Background(), WsResponse{
		Type:      "group_created",
		SessionId: session.Id,
		Content:   msg.Name,
	})
}

func (h *Handler) handleCreateDM(conn protocol.Connection, msg *WsMessage) error {
	uid := h.getUserId(conn)
	if uid <= 0 {
		return conn.SendJSON(context.Background(), WsResponse{
			Type:    "error",
			Content: "authentication required",
		})
	}
	if msg.TargetId <= 0 {
		return conn.SendJSON(context.Background(), WsResponse{
			Type:    "error",
			Content: "targetId is required",
		})
	}

	session, err := h.svcCtx.Store.CreateSession(chatcore.SessionTypeDM, "", uid, []int64{uid, msg.TargetId})
	if err != nil {
		return conn.SendJSON(context.Background(), WsResponse{
			Type:    "error",
			Content: err.Error(),
		})
	}

	return conn.SendJSON(context.Background(), WsResponse{
		Type:      "dm_created",
		SessionId: session.Id,
	})
}
