package auth

import (
	"context"
	"strings"

	domauth "gateway/internal/model/auth/domain/usecase"
	"gateway/internal/svc"
	"gateway/internal/types"

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

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

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

func (l *LogoutLogic) Logout() (*types.LogoutData, error) {
	if l.svcCtx.AuthToken == nil {
		return nil, errb.SysNotImplemented("auth token not configured")
	}
	raw := bearerAccessToken(l.ctx)
	if raw == "" {
		return nil, errb.AuthUnauthorized("missing access token")
	}
	if err := l.svcCtx.AuthToken.Logout(l.ctx, &domauth.LogoutRequest{AccessToken: raw}); err != nil {
		return nil, err
	}
	return &types.LogoutData{OK: true}, nil
}

type bearerTokenContextKey struct{}

// WithBearerAccessToken stores the raw Bearer access token for auth logic (e.g. logout).
func WithBearerAccessToken(ctx context.Context, token string) context.Context {
	return context.WithValue(ctx, bearerTokenContextKey{}, strings.TrimSpace(token))
}

func bearerAccessToken(ctx context.Context) string {
	if v, ok := ctx.Value(bearerTokenContextKey{}).(string); ok {
		return strings.TrimSpace(v)
	}
	return ""
}
