package auth

import (
	"context"
	"fmt"
	"strings"

	"apps/backend/internal/svc"
	"apps/backend/internal/types"

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

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

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

func (l *OAuthStartLogic) OAuthStart(req *types.AuthOAuthProviderPath) (resp *types.AuthOAuthStartData, err error) {
	p := strings.ToLower(strings.TrimSpace(req.Provider))
	if p == "" {
		p = "google"
	}
	// The current API accepts a verified provider credential in callback; it
	// does not yet expose a state-consuming browser callback, so returning a
	// fabricated authorization URL would be an authentication bypass.
	switch p {
	case "google":
		if strings.TrimSpace(l.svcCtx.Config.OAuth.GoogleClientID) == "" {
			return nil, fmt.Errorf("google OAuth is not configured")
		}
	case "line":
		if strings.TrimSpace(l.svcCtx.Config.OAuth.LineClientID) == "" || strings.TrimSpace(l.svcCtx.Config.OAuth.LineClientSecret) == "" {
			return nil, fmt.Errorf("LINE OAuth is not configured")
		}
	default:
		return nil, fmt.Errorf("unsupported OAuth provider: %s", p)
	}
	return nil, fmt.Errorf("interactive OAuth start is unavailable until Redis-backed state and PKCE callback are configured")
}
