package persona

import (
	"context"
	"fmt"

	"haixun-backend/internal/library/clock"
	copydraftdomain "haixun-backend/internal/model/copy_draft/domain/usecase"
	pqdomain "haixun-backend/internal/model/publish_queue/domain/usecase"
	"haixun-backend/internal/svc"
	"haixun-backend/internal/types"
)

type SchedulePersonaCopyDraftLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewSchedulePersonaCopyDraftLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SchedulePersonaCopyDraftLogic {
	return &SchedulePersonaCopyDraftLogic{ctx: ctx, svcCtx: svcCtx}
}

func (l *SchedulePersonaCopyDraftLogic) SchedulePersonaCopyDraft(req *types.SchedulePersonaCopyDraftHandlerReq) (*types.ScheduleCopyDraftsData, error) {
	tenantID, uid, err := actorFrom(l.ctx)
	if err != nil {
		return nil, err
	}
	if _, err := l.svcCtx.Persona.Get(l.ctx, tenantID, uid, req.ID); err != nil {
		return nil, err
	}
	if _, err := l.svcCtx.ThreadsAccount.Get(l.ctx, tenantID, uid, req.AccountID); err != nil {
		return nil, err
	}
	draft, err := l.svcCtx.CopyDraft.Get(l.ctx, tenantID, uid, req.ID, req.DraftID)
	if err != nil {
		return nil, err
	}
	if draft.PublishQueueID != "" {
		queueItems, err := l.svcCtx.PublishQueue.ListByIDs(l.ctx, tenantID, uid, []string{draft.PublishQueueID})
		if err != nil {
			return nil, err
		}
		if len(queueItems) > 0 {
			return &types.ScheduleCopyDraftsData{
				Scheduled: 1,
				List:      []types.PublishQueueItemData{publishQueueData(&queueItems[0])},
				Message:   fmt.Sprintf("草稿 %s 已排程", draft.ID),
			}, nil
		}
	}
	scheduledAt := req.ScheduledAt
	if scheduledAt <= 0 {
		scheduledAt = clock.NowUnixNano()
	}
	item, err := l.svcCtx.PublishQueue.Create(l.ctx, pqdomain.CreateRequest{
		TenantID: tenantID, OwnerUID: uid, AccountID: req.AccountID,
		PersonaID: req.ID, CopyMissionID: draft.CopyMissionID, CopyDraftID: draft.ID,
		Text: draft.Text, TopicTag: firstNonEmpty(req.TopicTag, draft.TopicTag), ScheduledAt: scheduledAt,
	})
	if err != nil {
		return nil, err
	}
	if _, err := l.svcCtx.CopyDraft.MarkScheduled(l.ctx, copydraftdomain.MarkScheduledRequest{
		TenantID: tenantID, OwnerUID: uid, PersonaID: req.ID, DraftID: draft.ID, QueueID: item.ID,
	}); err != nil {
		_ = l.svcCtx.PublishQueue.Delete(l.ctx, tenantID, uid, req.AccountID, item.ID)
		return nil, err
	}
	return &types.ScheduleCopyDraftsData{
		Scheduled: 1,
		List:      []types.PublishQueueItemData{publishQueueData(item)},
		Message:   fmt.Sprintf("已排程草稿 %s", draft.ID),
	}, nil
}

func firstNonEmpty(values ...string) string {
	for _, value := range values {
		if value != "" {
			return value
		}
	}
	return ""
}
