package channel

import (
	"github.com/tidbcloud/AgentTeam/internal/api/dto"
	"github.com/tidbcloud/AgentTeam/internal/store/channel"
	"github.com/tidbcloud/AgentTeam/internal/store/message"
)

func channelResponseFromSummary(summary message.ChannelSummary) dto.ChannelResponse {
	subsystem := summary.Subsystem
	if subsystem == message.ChannelSubsystemIM {
		subsystem = ""
	}
	return dto.ChannelResponse{
		ID:                summary.ChannelID,
		Name:              summary.Slug,
		Slug:              summary.Slug,
		DisplayName:       summary.DisplayName,
		Description:       summary.Description,
		Visibility:        summary.Visibility,
		Subsystem:         subsystem,
		Tutorial:          summary.Tutorial,
		TeamID:            summary.TeamID,
		TeamHandle:        summary.TeamHandle,
		TeamDisplayName:   summary.TeamDisplayName,
		Joined:            summary.Joined,
		CanInvite:         summary.CanInvite,
		CanManage:         summary.CanManage,
		Archived:          summary.Archived,
		SubscriptionState: summary.SubscriptionState,
		PinnedAt:          summary.PinnedAt,
	}
}

func discoverChannelResponseFromStore(channel channel.DiscoverableChannel) dto.DiscoverChannelResponse {
	return dto.DiscoverChannelResponse{
		ID:          channel.ChannelID,
		Name:        channel.Slug,
		Slug:        channel.Slug,
		DisplayName: channel.DisplayName,
		Description: channel.Description,
		Visibility:  channel.Visibility,
	}
}

func channelAccessResponseFromResolution(resolution channel.ChannelAccessResolution) dto.ChannelAccessResponse {
	response := dto.ChannelAccessResponse{Status: resolution.Status}
	switch resolution.Status {
	case channel.ChannelAccessStatusJoined:
		channelResponse := channelResponseFromSummary(resolution.Channel)
		response.Channel = &channelResponse
	case channel.ChannelAccessStatusPublicJoinable:
		joinableChannel := discoverChannelResponseFromStore(resolution.JoinableChannel)
		response.JoinableChannel = &joinableChannel
	}
	return response
}
