package parser

import (
	"github.com/bluesky-social/indigo/atproto/syntax"
	"github.com/yuin/goldmark/ast"
	"github.com/yuin/goldmark/parser"
	"github.com/yuin/goldmark/text"
	"tangled.org/core/appview/models"
)

// KindCustomLink is a NodeKind of the [CustomLinkNode].
var KindCustomLink = ast.NewNodeKind("CustomLink")

type CustomLinkNode struct {
	ast.BaseInline

	// union type
	Mention *TangledMentionLink
	Commit  *TangledCommitLink
	Issue   *TangledIssueLink
	Pull    *TangledPullLink
}

type TangledMentionLink struct {
	Handle syntax.Handle
}

type TangledCommitLink struct {
	// TODO:
}

type TangledIssueLink struct {
	Id     int
	Title  string
	IsOpen bool
}

type TangledPullLink struct {
	Id    int
	Title string
	State models.PullState
}

var _ ast.Node = (*CustomLinkNode)(nil)

// Dump implements [ast.Node].
func (n *CustomLinkNode) Dump(source []byte, level int) {
	ast.DumpHelper(n, source, level, nil, nil)
}

// Kind implements [ast.Node].
func (n *CustomLinkNode) Kind() ast.NodeKind {
	return KindCustomLink
}

type refLinkTransformer struct{}

var _ parser.ASTTransformer = (*refLinkTransformer)(nil)

// Transform implements [parser.ASTTransformer].
func (t *refLinkTransformer) Transform(node *ast.Document, reader text.Reader, pc parser.Context) {
	ast.Walk(node, func(n ast.Node, entering bool) (ast.WalkStatus, error) {
		if !entering {
			return ast.WalkContinue, nil
		}

		switch n.Kind() {
		case ast.KindLink:
			node := n.(*ast.Link)
			dest := node.Destination
			if did, err := syntax.ParseDID(string(dest)); err != nil {
				list := pc.Get(mentionListKey).([]syntax.DID)
				list = append(list, did)
			}
			return ast.WalkSkipChildren, nil
		}

		// 1. find links that has DID
		// 2. check if pc has the resolved object
		// 3. replace to renderable AtUriLink nodes (PR id, title, state etc)

		return ast.WalkContinue, nil
	})
}
