package scout

import (
	"context"
	"fmt"

	"apps/backend/internal/middleware"
	"apps/backend/internal/response"
	"apps/backend/internal/svc"
	"apps/backend/internal/types"

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

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

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

func (l *PromoteScoutPostLogic) PromoteScoutPost(req *types.ScoutPostIdPath) (*types.PromoteScoutPostData, error) {
	if l.svcCtx.Scout == nil || l.svcCtx.Radar == nil {
		return nil, response.Biz(503, 503001, "scout/radar not configured")
	}
	uid, ok := middleware.UIDFrom(l.ctx)
	if !ok {
		return nil, response.Biz(401, 401001, "missing authorization")
	}
	p, err := l.svcCtx.Scout.GetPost(l.ctx, uid, req.Id)
	if err != nil {
		return nil, err
	}
	if p.ScoutMode == "activity" || p.ScoutMode == "provider" {
		return nil, fmt.Errorf("this scout mode cannot be promoted to an opportunity")
	}
	externalID := p.ExternalID
	if externalID == "" {
		externalID = p.ID
	}
	o, err := l.svcCtx.Radar.PromoteFromScout(
		l.ctx, uid, p.ID, externalID, p.Permalink, p.Author, p.Text, p.PostedAt,
	)
	if err != nil {
		return nil, err
	}
	return &types.PromoteScoutPostData{
		OpportunityId: o.ID,
		Status:        o.Status,
		IntentBand:    o.IntentBand,
		IntentScore:   o.IntentScore,
	}, nil
}
