package persona

import (
	"context"
	"fmt"
	"strings"

	app "haixun-backend/internal/library/errors"
	"haixun-backend/internal/library/errors/code"
	jobdom "haixun-backend/internal/model/job/domain/usecase"
	"haixun-backend/internal/svc"
	"haixun-backend/internal/types"
)

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

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

func (l *StartPersonaRewriteDraftJobLogic) StartPersonaRewriteDraftJob(req *types.StartPersonaRewriteDraftJobHandlerReq) (*types.StartPersonaRewriteDraftJobData, error) {
	tenantID, uid, err := actorFrom(l.ctx)
	if err != nil {
		return nil, err
	}
	personaID := strings.TrimSpace(req.ID)
	accountID := strings.TrimSpace(req.AccountID)
	referenceText := strings.TrimSpace(req.ReferenceText)
	topic := strings.TrimSpace(req.Topic)
	if accountID == "" || referenceText == "" || topic == "" {
		return nil, app.For(code.Persona).InputMissingRequired("account_id, reference_text, and topic are required")
	}
	if _, err := l.svcCtx.Persona.Get(l.ctx, tenantID, uid, personaID); err != nil {
		return nil, err
	}
	if _, err := l.svcCtx.ThreadsAccount.Get(l.ctx, tenantID, uid, accountID); err != nil {
		return nil, err
	}
	credential, err := l.svcCtx.ThreadsAccount.ResolveMemberAiCredential(l.ctx, tenantID, uid)
	if err != nil {
		return nil, err
	}

	count := req.DraftCount
	if count <= 0 {
		count = 1
	}
	if count > 5 {
		count = 5
	}

	run, err := l.svcCtx.Job.CreateRun(l.ctx, jobdom.CreateRunRequest{
		TemplateType: "generate-rewrite-draft",
		Scope:        "persona",
		ScopeID:      personaID,
		TenantID:     tenantID,
		OwnerUID:     uid,
		Payload: map[string]any{
			"tenant_id":      tenantID,
			"owner_uid":      uid,
			"persona_id":     personaID,
			"account_id":     accountID,
			"reference_text": referenceText,
			"topic":          topic,
			"brief":          strings.TrimSpace(req.Brief),
			"save_label":     strings.TrimSpace(req.SaveLabel),
			"use_web_search": req.UseWebSearch,
			"draft_count":    count,
			"ai_provider":    credential.Provider,
			"ai_model":       credential.Model,
		},
	})
	if err != nil {
		return nil, err
	}

	return &types.StartPersonaRewriteDraftJobData{
		JobID:      run.ID.Hex(),
		Status:     string(run.Status),
		AiProvider: credential.Provider,
		AiModel:    credential.Model,
		Message:    fmt.Sprintf("貼文改寫已在背景執行（%s / %s），可自由切換頁面", credential.Provider, credential.Model),
	}, nil
}
