// Copyright 2026 printing-press-golden. Licensed under Apache-2.0. See LICENSE.
// Generated by CLI Printing Press (https://github.com/mvanhorn/cli-printing-press). DO NOT EDIT.

package cli

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"os"
	"strings"
	"time"

	"github.com/spf13/cobra"
	"printing-press-oauth2-pp-cli/internal/cliutil"
	"printing-press-oauth2-pp-cli/internal/config"
)

// OAuth2 client_credentials grant: 2-legged server-to-server flow.
// POST to TokenURL with form-encoded client_id/client_secret. No user
// redirect, no refresh_token. The client re-mints when within 60s of expiry.

func newAuthCmd(flags *rootFlags) *cobra.Command {
	cmd := &cobra.Command{
		Use:   "auth",
		Short: "Manage authentication for Printing Press Oauth2",
		RunE:  parentNoSubcommandRunE(flags),
	}

	cmd.AddCommand(newAuthLoginCmd(flags))
	cmd.AddCommand(newAuthStatusCmd(flags))
	cmd.AddCommand(newAuthSetTokenCmd(flags))
	cmd.AddCommand(newAuthLogoutCmd(flags))

	return cmd
}

func newAuthLoginCmd(flags *rootFlags) *cobra.Command {
	var (
		clientID     string
		clientSecret string
	)

	cmd := &cobra.Command{
		Use:   "login",
		Short: "Mint an OAuth2 bearer token via the client_credentials grant",
		Long: strings.TrimSpace(`
Mint an OAuth2 bearer token via POST https://api.cc.example/oauth/token with
grant_type=client_credentials and cache it on disk. Subsequent commands
auto-refresh the token before expiry.

Credentials default to PRINTING_PRESS_OAUTH2_CLIENT_ID (Client ID) and PRINTING_PRESS_OAUTH2_CLIENT_SECRET (Client Secret) environment variables.
`),
		Example: strings.Trim(`
  # Use env vars
  printing-press-oauth2-pp-cli auth login

  # Explicit credentials
  printing-press-oauth2-pp-cli auth login --client-id <id> --client-secret <secret>
`, "\n"),
		Annotations: map[string]string{"mcp:hidden": "true"},
		RunE: func(cmd *cobra.Command, args []string) error {
			if cliutil.IsVerifyEnv() {
				fmt.Fprintln(cmd.OutOrStdout(), "would mint token via OAuth2 client_credentials")
				return nil
			}

			if clientID == "" {
				clientID = os.Getenv("PRINTING_PRESS_OAUTH2_CLIENT_ID")
			}
			if clientSecret == "" {
				clientSecret = os.Getenv("PRINTING_PRESS_OAUTH2_CLIENT_SECRET")
			}
			if clientID == "" || clientSecret == "" {
				return authErr(fmt.Errorf("client ID and secret required (set --client-id/--client-secret or PRINTING_PRESS_OAUTH2_CLIENT_ID/PRINTING_PRESS_OAUTH2_CLIENT_SECRET)"))
			}

			cfg, err := config.Load(flags.configPath)
			if err != nil {
				return configErr(err)
			}

			tokenURL := cfg.TokenURL
			if tokenURL == "" {
				tokenURL = "https://api.cc.example/oauth/token"
			}
			tok, err := mintClientCredentialsToken(http.DefaultClient, tokenURL, clientID, clientSecret)
			if err != nil {
				return authErr(err)
			}

			cfg.AuthHeaderVal = ""
			// Guard against non-conformant servers that return expires_in: 0.
			// A zero-duration expiry resolves to time.Now(), which the client's
			// auto-refresh logic then treats as expired immediately.
			expiry := time.Time{}
			if tok.ExpiresIn > 0 {
				expiry = time.Now().Add(time.Duration(tok.ExpiresIn) * time.Second)
			}
			if err := cfg.SaveTokens(clientID, clientSecret, tok.AccessToken, "", expiry); err != nil {
				return configErr(fmt.Errorf("saving token: %w", err))
			}

			if expiry.IsZero() {
				fmt.Fprintln(cmd.OutOrStdout(), "Logged in. Token expiry not provided.")
			} else {
				fmt.Fprintf(cmd.OutOrStdout(), "Logged in. Token expires %s (in %ds).\n",
					expiry.Format(time.RFC3339), tok.ExpiresIn)
			}
			return nil
		},
	}
	cmd.Flags().StringVar(&clientID, "client-id", "", "OAuth2 Client ID; defaults to $PRINTING_PRESS_OAUTH2_CLIENT_ID")
	cmd.Flags().StringVar(&clientSecret, "client-secret", "", "OAuth2 Client Secret; defaults to $PRINTING_PRESS_OAUTH2_CLIENT_SECRET")

	return cmd
}

type tokenResponse struct {
	AccessToken string `json:"access_token"`
	ExpiresIn   int    `json:"expires_in"`
}

// mintClientCredentialsToken POSTs grant_type=client_credentials to the
// token endpoint and returns the parsed token response.
func mintClientCredentialsToken(httpClient *http.Client, tokenURL, clientID, clientSecret string) (*tokenResponse, error) {
	form := url.Values{
		"grant_type":    {"client_credentials"},
		"client_id":     {clientID},
		"client_secret": {clientSecret},
	}
	req, err := http.NewRequest(http.MethodPost, tokenURL, strings.NewReader(form.Encode()))
	if err != nil {
		return nil, fmt.Errorf("building token request: %w", err)
	}
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

	resp, err := httpClient.Do(req)
	if err != nil {
		return nil, fmt.Errorf("calling token endpoint: %w", err)
	}
	defer resp.Body.Close()

	body, _ := io.ReadAll(resp.Body)
	if resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("token endpoint returned HTTP %d: %s", resp.StatusCode, cliutil.SanitizeErrorBody(string(body)))
	}
	var tok tokenResponse
	if err := json.Unmarshal(body, &tok); err != nil {
		return nil, fmt.Errorf("parsing token response: %w", err)
	}
	if tok.AccessToken == "" {
		return nil, fmt.Errorf("token response missing access_token")
	}
	return &tok, nil
}

func newAuthStatusCmd(flags *rootFlags) *cobra.Command {
	return &cobra.Command{
		Use:     "status",
		Short:   "Show authentication status",
		Example: "  printing-press-oauth2-pp-cli auth status",
		RunE: func(cmd *cobra.Command, args []string) error {
			cfg, err := config.Load(flags.configPath)
			if err != nil {
				return configErr(err)
			}

			w := cmd.OutOrStdout()
			header := cfg.AuthHeader()
			authed := header != ""
			// JSON envelope: {authenticated, verified, source, config}. When not
			// authenticated, write the envelope first then return authErr
			// so exit code carries the auth-failure signal.
			if flags.asJSON {
				out := map[string]any{
					"authenticated": authed,
					"verified":      false,
					"source":        cfg.AuthSource,
					"config":        cfg.Path,
				}
				if printErr := printJSONFiltered(w, out, flags); printErr != nil {
					return printErr
				}
				if !authed {
					return authErr(fmt.Errorf("no credentials configured"))
				}
				return nil
			}
			if !authed {
				fmt.Fprintln(w, red("Not authenticated"))
				fmt.Fprintln(w, "")
				fmt.Fprintln(w, "Mint a token:")
				fmt.Fprintln(w, "  export PRINTING_PRESS_OAUTH2_CLIENT_ID=\"<client-id>\"")
				fmt.Fprintln(w, "  export PRINTING_PRESS_OAUTH2_CLIENT_SECRET=\"<client-secret>\"")
				fmt.Fprintf(w, "  printing-press-oauth2-pp-cli auth login\n")
				return authErr(fmt.Errorf("no credentials configured"))
			}

			fmt.Fprintln(w, green("Credentials present (not verified)"))
			fmt.Fprintf(w, "  Source: %s\n", cfg.AuthSource)
			fmt.Fprintf(w, "  Config: %s\n", cfg.Path)
			if !cfg.TokenExpiry.IsZero() {
				fmt.Fprintf(w, "  Expires: %s\n", cfg.TokenExpiry.Format(time.RFC3339))
			}
			return nil
		},
	}
}

func newAuthSetTokenCmd(flags *rootFlags) *cobra.Command {
	return &cobra.Command{
		Use:     "set-token <token>",
		Short:   "Save an API token to the config file (override the OAuth flow)",
		Example: "  printing-press-oauth2-pp-cli auth set-token <bearer-jwt>",
		Args:    cobra.ExactArgs(1),
		RunE: func(cmd *cobra.Command, args []string) error {
			cfg, err := config.Load(flags.configPath)
			if err != nil {
				return configErr(err)
			}
			cfg.AuthHeaderVal = ""
			if err := cfg.SaveTokens("", "", args[0], "", cfg.TokenExpiry); err != nil {
				return configErr(fmt.Errorf("saving token: %w", err))
			}
			// JSON envelope: {saved, config_path}.
			if flags.asJSON {
				return printJSONFiltered(cmd.OutOrStdout(), map[string]any{
					"saved":       true,
					"config_path": cfg.Path,
				}, flags)
			}
			fmt.Fprintf(cmd.OutOrStdout(), "Token saved to %s\n", cfg.Path)
			return nil
		},
	}
}

func newAuthLogoutCmd(flags *rootFlags) *cobra.Command {
	return &cobra.Command{
		Use:     "logout",
		Short:   "Clear stored credentials",
		Example: "  printing-press-oauth2-pp-cli auth logout",
		RunE: func(cmd *cobra.Command, args []string) error {
			cfg, err := config.Load(flags.configPath)
			if err != nil {
				return configErr(err)
			}
			if err := cfg.ClearTokens(); err != nil {
				return configErr(fmt.Errorf("clearing tokens: %w", err))
			}

			// Identify which (if any) auth env var is still exported so the
			// JSON envelope and the human prose can both surface it.
			envStillSet := ""
			if envStillSet == "" && os.Getenv("PRINTING_PRESS_OAUTH2_CLIENT_ID") != "" {
				envStillSet = "PRINTING_PRESS_OAUTH2_CLIENT_ID"
			}
			if envStillSet == "" && os.Getenv("PRINTING_PRESS_OAUTH2_CLIENT_SECRET") != "" {
				envStillSet = "PRINTING_PRESS_OAUTH2_CLIENT_SECRET"
			}

			// JSON envelope: {cleared: true, note?: "<env_var> env var is still set"}.
			if flags.asJSON {
				out := map[string]any{"cleared": true}
				if envStillSet != "" {
					out["note"] = envStillSet + " env var is still set"
				}
				return printJSONFiltered(cmd.OutOrStdout(), out, flags)
			}

			if envStillSet != "" {
				fmt.Fprintf(cmd.OutOrStdout(), "Config cleared. Note: %s env var is still set.\n", envStillSet)
				return nil
			}
			fmt.Fprintln(cmd.OutOrStdout(), "Logged out. Credentials cleared.")
			return nil
		},
	}
}
