package threads

import (
	"context"
	"encoding/json"
	"strings"
	"time"

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

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

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

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

// ImportThreadsAccountSession — 擴充 POST .../session/import
// 相容舊版 Chrome 擴充：body { storageState }；寫入 scout crawler-session 供 dev 模式海巡。
func (l *ImportThreadsAccountSessionLogic) ImportThreadsAccountSession(req *types.ImportThreadsAccountSessionReq) (*types.ImportThreadsAccountSessionData, error) {
	if l.svcCtx.Threads == nil {
		return nil, response.Biz(503, 503001, "threads module not configured")
	}
	uid, ok := middleware.UIDFrom(l.ctx)
	if !ok {
		return nil, response.Biz(401, 401001, "missing authorization")
	}

	state := strings.TrimSpace(req.StorageState)
	if state == "" {
		return nil, response.Biz(400, 400010, "storageState is required")
	}
	if err := validateStorageStateJSON(state); err != nil {
		return &types.ImportThreadsAccountSessionData{
			Success:   false,
			Valid:     false,
			Synced:    false,
			AccountId: req.Id,
			Message:   err.Error(),
			UpdateAt:  time.Now().UTC().UnixNano(),
		}, nil
	}

	acc, err := l.svcCtx.Threads.Get(l.ctx, req.Id)
	if err != nil {
		return nil, err
	}
	if acc.OwnerUID != uid {
		return nil, response.Biz(403, 403001, "forbidden")
	}

	// 寫入爬蟲 session（dev 模式海巡用）
	if l.svcCtx.Scout != nil {
		if err := l.svcCtx.Scout.SetCrawlerSession(l.ctx, uid, state); err != nil {
			return nil, err
		}
	}

	now := time.Now().UTC().UnixNano()
	return &types.ImportThreadsAccountSessionData{
		Success:   true,
		Valid:     true,
		Synced:    true,
		AccountId: acc.ID,
		Username:  acc.Username,
		Message:   "Chrome session 已同步（爬蟲 session）",
		UpdateAt:  now,
	}, nil
}

func validateStorageStateJSON(raw string) error {
	var payload struct {
		Cookies []json.RawMessage `json:"cookies"`
	}
	if err := json.Unmarshal([]byte(raw), &payload); err != nil {
		return errInvalidStorage("storageState is not valid JSON")
	}
	if len(payload.Cookies) == 0 {
		return errInvalidStorage("storageState must include cookies array")
	}
	return nil
}

type storageStateError string

func (e storageStateError) Error() string { return string(e) }

func errInvalidStorage(msg string) error { return storageStateError(msg) }
