package auth

import (
	"context"
	"crypto/rand"
	"encoding/base64"
	"fmt"
	"log/slog"
	"os"

	"github.com/jackc/pgx/v5/pgxpool"
	"golang.org/x/crypto/bcrypt"

	"git.fabledsword.com/bvandeusen/minstrel/internal/config"
	"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
)

// Bootstrap creates the initial admin user when the users table is empty AND
// the config supplies a bootstrap username. A blank password means "generate a
// random one and print it once on stderr" — suitable for first-run setups
// where the operator is watching the logs.
func Bootstrap(ctx context.Context, pool *pgxpool.Pool, cfg config.AdminBootstrapConfig, logger *slog.Logger) error {
	if cfg.Username == "" {
		return nil
	}

	q := dbq.New(pool)
	count, err := q.CountUsers(ctx)
	if err != nil {
		return fmt.Errorf("auth: count users: %w", err)
	}
	if count > 0 {
		return nil
	}

	password := cfg.Password
	passwordGenerated := false
	if password == "" {
		p, err := randomToken(18)
		if err != nil {
			return fmt.Errorf("auth: generate password: %w", err)
		}
		password = p
		passwordGenerated = true
	}

	hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	if err != nil {
		return fmt.Errorf("auth: hash password: %w", err)
	}

	apiToken, err := randomToken(32)
	if err != nil {
		return fmt.Errorf("auth: generate api token: %w", err)
	}

	user, err := q.CreateUser(ctx, dbq.CreateUserParams{
		Username:     cfg.Username,
		PasswordHash: string(hash),
		ApiToken:     apiToken,
		IsAdmin:      true,
	})
	if err != nil {
		return fmt.Errorf("auth: insert admin: %w", err)
	}

	// Mirror the bootstrap password into subsonic_password so Subsonic clients
	// (Feishin, Symfonium, …) can authenticate via t+s without the operator
	// having to run a separate SQL update after first boot. This is plaintext
	// at rest — the cost of Subsonic's legacy auth — and matches what servers
	// like Navidrome do. Operators who don't want a plaintext copy can clear
	// it later with SetSubsonicPassword(nil).
	subPass := password
	if err := q.SetSubsonicPassword(ctx, dbq.SetSubsonicPasswordParams{
		ID:               user.ID,
		SubsonicPassword: &subPass,
	}); err != nil {
		return fmt.Errorf("auth: set subsonic password: %w", err)
	}

	logger.Info("admin bootstrapped", "username", cfg.Username, "user_id", user.ID.String())
	if passwordGenerated {
		fmt.Fprintf(os.Stderr, "\n--- minstrel admin bootstrap (shown once) ---\nusername:  %s\npassword:  %s\napi_token: %s\n(password works for both the native UI and Subsonic clients)\n---\n\n",
			cfg.Username, password, apiToken)
	} else {
		fmt.Fprintf(os.Stderr, "\n--- minstrel admin api token (shown once) ---\nusername:  %s\napi_token: %s\n(your configured password now also works for Subsonic clients)\n---\n\n",
			cfg.Username, apiToken)
	}
	return nil
}

// randomToken returns a URL-safe base64 string backed by n random bytes.
func randomToken(n int) (string, error) {
	b := make([]byte, n)
	if _, err := rand.Read(b); err != nil {
		return "", err
	}
	return base64.RawURLEncoding.EncodeToString(b), nil
}
