// Code scaffolded by goctl. Safe to edit.
// goctl 1.10.1

package threads_account

import (
	"context"

	"haixun-backend/internal/svc"
	"haixun-backend/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetPublishDashboardSummaryLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetPublishDashboardSummaryLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetPublishDashboardSummaryLogic {
	return &GetPublishDashboardSummaryLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetPublishDashboardSummaryLogic) GetPublishDashboardSummary() (resp *types.PublishDashboardSummaryData, err error) {
	tenantID, uid, err := actorFrom(l.ctx)
	if err != nil {
		return nil, err
	}
	accounts, err := l.svcCtx.ThreadsAccount.List(l.ctx, tenantID, uid)
	if err != nil {
		return nil, err
	}
	resp = &types.PublishDashboardSummaryData{List: []types.PublishDashboardAccountSummary{}}
	for _, account := range accounts.List {
		health, hErr := l.svcCtx.PublishQueue.ListPublishHealth(l.ctx, tenantID, uid, account.ID, 1, 10)
		if hErr != nil {
			continue
		}
		guard, _ := l.svcCtx.PublishGuard.Get(l.ctx, tenantID, uid, account.ID)
		slots, _ := l.svcCtx.PublishQueue.ListSlotInsights(l.ctx, tenantID, uid, account.ID, "Asia/Taipei")
		bestSlot, lowSlot := "", ""
		for _, slot := range slots {
			if bestSlot == "" && slot.Recommendation == "recommended" {
				bestSlot = slot.Time
			}
			if lowSlot == "" && slot.Recommendation == "low" {
				lowSlot = slot.Time
			}
		}
		row := types.PublishDashboardAccountSummary{
			AccountID: account.ID, AccountName: firstNonEmpty(account.DisplayName, account.Username, account.ID),
			PendingScheduled: health.Summary.PendingScheduled, FailedCount: health.Summary.FailedCount,
			Published7d: health.Summary.Published7d, TotalLikes7d: health.Summary.TotalLikes7d,
			TotalReplies7d: health.Summary.TotalReplies7d, BestSlot: bestSlot, LowSlot: lowSlot,
		}
		if guard != nil {
			row.Paused = guard.Paused
		}
		resp.List = append(resp.List, row)
		resp.TotalPending += row.PendingScheduled
		resp.TotalFailed += row.FailedCount
		resp.TotalPublished7d += row.Published7d
		resp.TotalLikes7d += row.TotalLikes7d
		resp.TotalReplies7d += row.TotalReplies7d
	}
	return resp, nil
}
