package service

import (
	"context"
	"errors"
	"testing"

	"oci-portal/internal/crypto"
	"oci-portal/internal/model"
)

// newCredEnv 复用 totp 环境并注入 settings(密码登录开关落 Setting 表)。
func newCredEnv(t *testing.T) *AuthService {
	t.Helper()
	auth, db := newTotpEnv(t)
	cipher, err := crypto.NewCipher("test-key")
	if err != nil {
		t.Fatalf("new cipher: %v", err)
	}
	auth.SetNotifier(nil, NewSettingService(db, cipher))
	return auth
}

func TestUpdateCredentials(t *testing.T) {
	auth := newCredEnv(t)
	ctx := context.Background()

	// 当前密码错误
	_, err := auth.UpdateCredentials(ctx, "admin", UpdateCredentialsInput{NewPassword: "newpass-123", CurrentPassword: "wrong"})
	if !errors.Is(err, ErrCredentialConfirm) {
		t.Fatalf("wrong current password: err = %v, want ErrCredentialConfirm", err)
	}
	// 短密码 / 无变更均拒绝
	_, err = auth.UpdateCredentials(ctx, "admin", UpdateCredentialsInput{NewPassword: "short", CurrentPassword: "pass123"})
	if !errors.Is(err, ErrCredentialInvalid) {
		t.Fatalf("short password: err = %v, want ErrCredentialInvalid", err)
	}
	_, err = auth.UpdateCredentials(ctx, "admin", UpdateCredentialsInput{NewUsername: "admin", CurrentPassword: "pass123"})
	if !errors.Is(err, ErrCredentialInvalid) {
		t.Fatalf("no-op change: err = %v, want ErrCredentialInvalid", err)
	}

	// 同时改名改密
	_, err = auth.UpdateCredentials(ctx, "admin", UpdateCredentialsInput{
		NewUsername: "root", NewPassword: "newpass-123", CurrentPassword: "pass123",
	})
	if err != nil {
		t.Fatalf("UpdateCredentials: %v", err)
	}
	if _, _, err := auth.Login(ctx, "admin", "pass123", "127.0.0.1", ""); !errors.Is(err, ErrInvalidCredentials) {
		t.Errorf("old username login: err = %v, want ErrInvalidCredentials", err)
	}
	if _, _, err := auth.Login(ctx, "root", "newpass-123", "127.0.0.2", ""); err != nil {
		t.Errorf("new credentials login: %v", err)
	}
}

func TestPasswordLoginToggle(t *testing.T) {
	auth := newCredEnv(t)
	ctx := context.Background()

	// 未绑定外部身份不可禁用
	if err := auth.SetPasswordLoginDisabled(ctx, "admin", true); !errors.Is(err, ErrNeedIdentity) {
		t.Fatalf("disable without identity: err = %v, want ErrNeedIdentity", err)
	}

	var user model.User
	if err := auth.db.Where("username = ?", "admin").First(&user).Error; err != nil {
		t.Fatalf("find admin: %v", err)
	}
	ident := model.UserIdentity{UserID: user.ID, Provider: "github", Subject: "1", Display: "tester"}
	if err := auth.db.Create(&ident).Error; err != nil {
		t.Fatalf("seed identity: %v", err)
	}

	if err := auth.SetPasswordLoginDisabled(ctx, "admin", true); err != nil {
		t.Fatalf("disable with identity: %v", err)
	}
	if off, err := auth.PasswordLoginDisabled(ctx); err != nil || !off {
		t.Fatalf("PasswordLoginDisabled = %v, %v; want true", off, err)
	}
	// 密码登录被拒且不计失败(正确密码亦拒)
	if _, _, err := auth.Login(ctx, "admin", "pass123", "127.0.0.1", ""); !errors.Is(err, ErrPasswordLoginDisabled) {
		t.Fatalf("login while disabled: err = %v, want ErrPasswordLoginDisabled", err)
	}

	// 开关开着不能解绑最后一个身份
	oauth := NewOAuthService(auth.db, nil, auth)
	if err := oauth.Unbind(ctx, "admin", ident.ID); !errors.Is(err, ErrLastIdentity) {
		t.Fatalf("unbind last identity: err = %v, want ErrLastIdentity", err)
	}

	// 恢复密码登录后可解绑、可登录
	if err := auth.SetPasswordLoginDisabled(ctx, "admin", false); err != nil {
		t.Fatalf("enable password login: %v", err)
	}
	if err := oauth.Unbind(ctx, "admin", ident.ID); err != nil {
		t.Fatalf("unbind after enable: %v", err)
	}
	if _, _, err := auth.Login(ctx, "admin", "pass123", "127.0.0.3", ""); err != nil {
		t.Errorf("login after enable: %v", err)
	}
}
