package mcp

import (
	"context"

	"github.com/google/uuid"

	"github.com/yan1h/agent-coding-workflow/internal/infra/errs"
	"github.com/yan1h/agent-coding-workflow/internal/project"
	"github.com/yan1h/agent-coding-workflow/internal/user"
)

// CallerResolver 把 MCP AuthSession 转成 project.Caller。
type CallerResolver struct {
	users user.Service
}

func NewCallerResolver(users user.Service) *CallerResolver {
	return &CallerResolver{users: users}
}

func (r *CallerResolver) Resolve(ctx context.Context) (project.Caller, error) {
	sess, ok := FromContext(ctx)
	if !ok {
		return project.Caller{}, errs.New(errs.CodeInternal,
			"mcp: AuthSession missing from context (middleware order bug)")
	}
	uid, err := uuid.Parse(sess.UserID)
	if err != nil {
		return project.Caller{}, errs.Wrap(err, errs.CodeInternal, "parse user_id from auth session")
	}
	u, err := r.users.Get(ctx, uid)
	if err != nil {
		return project.Caller{}, err
	}
	return project.Caller{UserID: uid, IsAdmin: u.IsAdmin}, nil
}
