//go:build integration

package inttest

import (
	"context"
	"errors"
	"regexp"
	"slices"
	"testing"
	"time"

	"github.com/google/uuid"

	"scrabble/backend/internal/account"
)

// capturingMailer records the last message instead of sending it, so tests can
// recover the confirm-code from the body.
type capturingMailer struct{ lastBody string }

func (m *capturingMailer) Send(_ context.Context, msg account.Message) error {
	m.lastBody = msg.Text
	return nil
}

var sixDigit = regexp.MustCompile(`\d{6}`)

// TestEmailConfirmFlow covers the happy path: request a code, confirm it, and the
// email becomes a confirmed identity of the account.
func TestEmailConfirmFlow(t *testing.T) {
	ctx := context.Background()
	store := account.NewStore(testDB)
	mailer := &capturingMailer{}
	svc := account.NewEmailService(store, mailer, "https://erudit-game.ru")

	acc := provisionAccount(t)
	email := "user-" + uuid.NewString() + "@example.com"

	if err := svc.RequestCode(ctx, acc, email); err != nil {
		t.Fatalf("request code: %v", err)
	}
	code := sixDigit.FindString(mailer.lastBody)
	if code == "" {
		t.Fatalf("no code in mail body %q", mailer.lastBody)
	}

	// A wrong code is rejected without confirming.
	if _, err := svc.ConfirmCode(ctx, acc, email, "000000"); !errors.Is(err, account.ErrCodeMismatch) && !errors.Is(err, account.ErrTooManyAttempts) {
		t.Fatalf("wrong code = %v, want mismatch", err)
	}
	got, err := svc.ConfirmCode(ctx, acc, email, code)
	if err != nil {
		t.Fatalf("confirm code: %v", err)
	}
	if got.ID != acc {
		t.Errorf("confirmed account = %s, want %s", got.ID, acc)
	}
	if !identityConfirmed(t, account.KindEmail, email) {
		t.Error("email identity must be confirmed after a correct code")
	}
}

// TestEmailAlreadyTakenByAnotherAccount refuses to bind an email confirmed by a
// different account (combining two accounts is the separate link/merge flow).
func TestEmailAlreadyTakenByAnotherAccount(t *testing.T) {
	ctx := context.Background()
	store := account.NewStore(testDB)
	mailer := &capturingMailer{}
	svc := account.NewEmailService(store, mailer, "https://erudit-game.ru")

	owner := provisionAccount(t)
	email := "taken-" + uuid.NewString() + "@example.com"
	if err := svc.RequestCode(ctx, owner, email); err != nil {
		t.Fatalf("owner request: %v", err)
	}
	if _, err := svc.ConfirmCode(ctx, owner, email, sixDigit.FindString(mailer.lastBody)); err != nil {
		t.Fatalf("owner confirm: %v", err)
	}

	other := provisionAccount(t)
	if err := svc.RequestCode(ctx, other, email); !errors.Is(err, account.ErrEmailTaken) {
		t.Fatalf("other request = %v, want ErrEmailTaken", err)
	}
}

// TestEmailCodeExpires rejects a code past its TTL (backdated directly).
func TestEmailCodeExpires(t *testing.T) {
	ctx := context.Background()
	store := account.NewStore(testDB)
	mailer := &capturingMailer{}
	svc := account.NewEmailService(store, mailer, "https://erudit-game.ru")

	acc := provisionAccount(t)
	email := "expire-" + uuid.NewString() + "@example.com"
	if err := svc.RequestCode(ctx, acc, email); err != nil {
		t.Fatalf("request: %v", err)
	}
	code := sixDigit.FindString(mailer.lastBody)
	if _, err := testDB.ExecContext(ctx,
		`UPDATE backend.email_confirmations SET expires_at = now() - interval '1 minute' WHERE account_id = $1`, acc); err != nil {
		t.Fatalf("backdate expiry: %v", err)
	}
	if _, err := svc.ConfirmCode(ctx, acc, email, code); !errors.Is(err, account.ErrCodeExpired) {
		t.Fatalf("confirm expired = %v, want ErrCodeExpired", err)
	}
}

// TestEmailTooManyAttempts locks a code after the attempt cap.
func TestEmailTooManyAttempts(t *testing.T) {
	ctx := context.Background()
	store := account.NewStore(testDB)
	mailer := &capturingMailer{}
	svc := account.NewEmailService(store, mailer, "https://erudit-game.ru")

	acc := provisionAccount(t)
	email := "lock-" + uuid.NewString() + "@example.com"
	if err := svc.RequestCode(ctx, acc, email); err != nil {
		t.Fatalf("request: %v", err)
	}
	// Five wrong tries are mismatches; the sixth is locked out.
	for i := 0; i < 5; i++ {
		if _, err := svc.ConfirmCode(ctx, acc, email, "999999"); !errors.Is(err, account.ErrCodeMismatch) {
			t.Fatalf("attempt %d = %v, want ErrCodeMismatch", i+1, err)
		}
	}
	if _, err := svc.ConfirmCode(ctx, acc, email, "999999"); !errors.Is(err, account.ErrTooManyAttempts) {
		t.Fatalf("after cap = %v, want ErrTooManyAttempts", err)
	}
}

// TestUpdateProfilePersists writes a full profile and reads it back.
func TestUpdateProfilePersists(t *testing.T) {
	ctx := context.Background()
	store := account.NewStore(testDB)
	acc := provisionAccount(t)

	// A fresh registered account defaults to both Russian-alphabet games (the DB-level
	// column default); the lifecycle around it is covered by TestVariantPreferenceDefaults.
	if def, err := store.GetByID(ctx, acc); err != nil {
		t.Fatalf("get default: %v", err)
	} else if want := account.DefaultVariantPreferences; !slices.Equal(def.VariantPreferences, want) {
		t.Errorf("default variant preferences = %v, want %v", def.VariantPreferences, want)
	}

	updated, err := store.UpdateProfile(ctx, acc, account.ProfileUpdate{
		DisplayName:         "Kaya",
		PreferredLanguage:   "ru",
		TimeZone:            "Europe/Moscow",
		BlockChat:           true,
		BlockFriendRequests: true,
		VariantPreferences:  []string{"scrabble_en", "erudit_ru"},
	})
	if err != nil {
		t.Fatalf("update profile: %v", err)
	}
	if updated.DisplayName != "Kaya" || updated.PreferredLanguage != "ru" || updated.TimeZone != "Europe/Moscow" {
		t.Errorf("profile not applied: %+v", updated)
	}
	if !updated.BlockChat || !updated.BlockFriendRequests {
		t.Errorf("block toggles not applied: %+v", updated)
	}
	reloaded, err := store.GetByID(ctx, acc)
	if err != nil {
		t.Fatalf("reload: %v", err)
	}
	if reloaded.TimeZone != "Europe/Moscow" || !reloaded.BlockChat {
		t.Errorf("profile did not persist: %+v", reloaded)
	}
	// The text[] column round-trips and is stored canonically (Erudit-first).
	if want := []string{"erudit_ru", "scrabble_en"}; !slices.Equal(reloaded.VariantPreferences, want) {
		t.Errorf("variant preferences = %v, want %v", reloaded.VariantPreferences, want)
	}
}

// TestUpdateProfileOffsetTimezone checks the UTC-offset timezone: it is
// accepted, persisted verbatim, and resolved to the right fixed offset.
func TestUpdateProfileOffsetTimezone(t *testing.T) {
	ctx := context.Background()
	store := account.NewStore(testDB)
	acc := provisionAccount(t)

	updated, err := store.UpdateProfile(ctx, acc, account.ProfileUpdate{
		DisplayName:        "Kaya",
		PreferredLanguage:  "en",
		TimeZone:           "+03:00",
		VariantPreferences: []string{"erudit_ru"},
	})
	if err != nil {
		t.Fatalf("update with offset timezone: %v", err)
	}
	if updated.TimeZone != "+03:00" {
		t.Fatalf("timezone = %q, want +03:00", updated.TimeZone)
	}
	if _, off := time.Date(2024, 1, 1, 12, 0, 0, 0, account.ResolveZone(updated.TimeZone)).Zone(); off != 3*3600 {
		t.Fatalf("ResolveZone offset = %d, want 10800", off)
	}
}

// TestEmailLoginFlow covers the email-as-login path: a code is mailed to
// a new address, verifying it provisions and returns the owning account, and a
// second login for the same address resolves to that same account (a returning
// user), with the identity confirmed.
func TestEmailLoginFlow(t *testing.T) {
	ctx := context.Background()
	mailer := &capturingMailer{}
	svc := account.NewEmailService(account.NewStore(testDB), mailer, "https://erudit-game.ru")
	email := "login-" + uuid.NewString() + "@example.com"

	accountID, err := svc.RequestLoginCode(ctx, email, "+02:00", "en", false)
	if err != nil {
		t.Fatalf("request login code: %v", err)
	}
	code := sixDigit.FindString(mailer.lastBody)
	if code == "" {
		t.Fatalf("no code in mail body %q", mailer.lastBody)
	}

	acc, err := svc.LoginWithCode(ctx, email, code)
	if err != nil {
		t.Fatalf("login with code: %v", err)
	}
	if acc.ID != accountID {
		t.Errorf("login account = %s, want %s", acc.ID, accountID)
	}
	if acc.IsGuest {
		t.Error("an email account must be durable, not a guest")
	}
	if acc.TimeZone != "+02:00" {
		t.Errorf("TimeZone = %q, want the +02:00 seeded at the request step", acc.TimeZone)
	}
	if !identityConfirmed(t, account.KindEmail, email) {
		t.Error("the email identity must be confirmed after login")
	}

	// A second login for the same email is the returning user: same account.
	if _, err := svc.RequestLoginCode(ctx, email, "", "ru", false); err != nil {
		t.Fatalf("second request: %v", err)
	}
	acc2, err := svc.LoginWithCode(ctx, email, sixDigit.FindString(mailer.lastBody))
	if err != nil {
		t.Fatalf("second login: %v", err)
	}
	if acc2.ID != accountID {
		t.Errorf("returning login account = %s, want %s", acc2.ID, accountID)
	}
}

// TestEmailLoginProvisionsGuestUntilConfirmed covers the squat fix: an email-login
// account is a guest (reapable, so an abandoned never-confirmed login frees its
// address) until the code is confirmed, which promotes it to a durable account.
func TestEmailLoginProvisionsGuestUntilConfirmed(t *testing.T) {
	ctx := context.Background()
	store := account.NewStore(testDB)
	mailer := &capturingMailer{}
	svc := account.NewEmailService(store, mailer, "https://erudit-game.ru")
	email := "squat-" + uuid.NewString() + "@example.com"

	id, err := svc.RequestLoginCode(ctx, email, "", "en", false)
	if err != nil {
		t.Fatalf("request login code: %v", err)
	}
	before, err := store.GetByID(ctx, id)
	if err != nil {
		t.Fatalf("get before confirm: %v", err)
	}
	if !before.IsGuest {
		t.Error("an unconfirmed email-login account must be a guest so it is reapable")
	}

	if _, err := svc.LoginWithCode(ctx, email, sixDigit.FindString(mailer.lastBody)); err != nil {
		t.Fatalf("login: %v", err)
	}
	after, err := store.GetByID(ctx, id)
	if err != nil {
		t.Fatalf("get after confirm: %v", err)
	}
	if after.IsGuest {
		t.Error("confirming the login must clear the guest flag (promote to durable)")
	}
}

// TestEmailLoginPWAOmitsLink: a login requested from an installed PWA (pwa=true) mails only the
// code — no one-tap confirm link, which would otherwise open in a separate browser out of the
// PWA's reach. A non-PWA request keeps the link.
func TestEmailLoginPWAOmitsLink(t *testing.T) {
	ctx := context.Background()
	mailer := &capturingMailer{}
	svc := account.NewEmailService(account.NewStore(testDB), mailer, "https://erudit-game.ru")

	pwaEmail := "pwa-login-" + uuid.NewString() + "@example.com"
	if _, err := svc.RequestLoginCode(ctx, pwaEmail, "", "en", true); err != nil {
		t.Fatalf("pwa request login: %v", err)
	}
	if sixDigit.FindString(mailer.lastBody) == "" {
		t.Errorf("pwa login mail must still carry the code, body %q", mailer.lastBody)
	}
	if confirmToken.MatchString(mailer.lastBody) {
		t.Errorf("pwa login mail must omit the one-tap confirm link, body %q", mailer.lastBody)
	}

	webEmail := "web-login-" + uuid.NewString() + "@example.com"
	if _, err := svc.RequestLoginCode(ctx, webEmail, "", "en", false); err != nil {
		t.Fatalf("web request login: %v", err)
	}
	if !confirmToken.MatchString(mailer.lastBody) {
		t.Errorf("non-pwa login mail must keep the one-tap confirm link, body %q", mailer.lastBody)
	}
}

// confirmToken extracts the one-tap deeplink token from the /app/#/confirm/<token> link
// the branded email carries.
var confirmToken = regexp.MustCompile(`/confirm/([A-Za-z0-9_-]+)`)

func tokenFromMail(t *testing.T, body string) string {
	t.Helper()
	m := confirmToken.FindStringSubmatch(body)
	if m == nil {
		t.Fatalf("no confirm token in mail body %q", body)
	}
	return m[1]
}

// TestConfirmByTokenLogin: the one-tap deeplink token completes an email login,
// clearing the guest flag.
func TestConfirmByTokenLogin(t *testing.T) {
	ctx := context.Background()
	store := account.NewStore(testDB)
	mailer := &capturingMailer{}
	svc := account.NewEmailService(store, mailer, "https://erudit-game.ru")
	email := "tok-login-" + uuid.NewString() + "@example.com"

	id, err := svc.RequestLoginCode(ctx, email, "", "en", false)
	if err != nil {
		t.Fatalf("request login: %v", err)
	}
	res, err := svc.ConfirmByToken(ctx, tokenFromMail(t, mailer.lastBody))
	if err != nil {
		t.Fatalf("confirm by token: %v", err)
	}
	if !res.IsLogin() || res.Account != id {
		t.Fatalf("login result = %+v, want login for %s", res, id)
	}
	if !identityConfirmed(t, account.KindEmail, email) {
		t.Error("email identity must be confirmed after the token login")
	}
	if acc, _ := store.GetByID(ctx, id); acc.IsGuest {
		t.Error("the token login must clear the guest flag")
	}
}

// TestConfirmByTokenLink: the token attaches a free email to the requesting account.
func TestConfirmByTokenLink(t *testing.T) {
	ctx := context.Background()
	store := account.NewStore(testDB)
	mailer := &capturingMailer{}
	svc := account.NewEmailService(store, mailer, "https://erudit-game.ru")
	acc := provisionAccount(t)
	email := "tok-link-" + uuid.NewString() + "@example.com"

	if err := svc.RequestLinkCode(ctx, acc, email); err != nil {
		t.Fatalf("request link: %v", err)
	}
	res, err := svc.ConfirmByToken(ctx, tokenFromMail(t, mailer.lastBody))
	if err != nil {
		t.Fatalf("confirm by token: %v", err)
	}
	if res.IsLogin() || res.NeedsMerge || res.Account != acc {
		t.Fatalf("link result = %+v, want a plain link for %s", res, acc)
	}
	if !identityConfirmed(t, account.KindEmail, email) {
		t.Error("email identity must be confirmed after the token link")
	}
}

// TestConfirmByTokenLinkMerge: a token for an address owned by another account signals
// a merge (leaving the token unconsumed for the interactive step).
func TestConfirmByTokenLinkMerge(t *testing.T) {
	ctx := context.Background()
	store := account.NewStore(testDB)
	mailer := &capturingMailer{}
	svc := account.NewEmailService(store, mailer, "https://erudit-game.ru")
	email := "tok-merge-" + uuid.NewString() + "@example.com"

	owner := provisionAccount(t)
	if err := svc.RequestCode(ctx, owner, email); err != nil {
		t.Fatalf("owner request: %v", err)
	}
	if _, err := svc.ConfirmCode(ctx, owner, email, sixDigit.FindString(mailer.lastBody)); err != nil {
		t.Fatalf("owner confirm: %v", err)
	}

	other := provisionAccount(t)
	if err := svc.RequestLinkCode(ctx, other, email); err != nil {
		t.Fatalf("link request: %v", err)
	}
	res, err := svc.ConfirmByToken(ctx, tokenFromMail(t, mailer.lastBody))
	if err != nil {
		t.Fatalf("confirm by token: %v", err)
	}
	if !res.NeedsMerge || res.MergeOwner != owner {
		t.Fatalf("merge result = %+v, want NeedsMerge with owner=%s", res, owner)
	}
}

// TestEmailAccountSeedsDisplayName seeds a new email account's display name from the
// email's local part, so an email login is not left nameless.
func TestEmailAccountSeedsDisplayName(t *testing.T) {
	ctx := context.Background()
	store := account.NewStore(testDB)
	svc := account.NewEmailService(store, &capturingMailer{}, "https://erudit-game.ru")
	local := "kaya-" + uuid.NewString()[:8]

	id, err := svc.RequestLoginCode(ctx, local+"@example.com", "", "en", false)
	if err != nil {
		t.Fatalf("request login: %v", err)
	}
	acc, err := store.GetByID(ctx, id)
	if err != nil {
		t.Fatalf("get: %v", err)
	}
	if acc.DisplayName != local {
		t.Errorf("display name = %q, want the email local part %q", acc.DisplayName, local)
	}
}

// TestConfirmByTokenLinkClearsGuest: binding an email to a guest via the deeplink
// promotes the guest to a durable account (the deeplink path must match the
// code-based link flow, which clears the guest flag).
func TestConfirmByTokenLinkClearsGuest(t *testing.T) {
	ctx := context.Background()
	store := account.NewStore(testDB)
	mailer := &capturingMailer{}
	svc := account.NewEmailService(store, mailer, "https://erudit-game.ru")
	guest, err := store.ProvisionGuest(ctx, "", "")
	if err != nil {
		t.Fatalf("provision guest: %v", err)
	}
	email := "guest-link-" + uuid.NewString() + "@example.com"

	if err := svc.RequestLinkCode(ctx, guest.ID, email); err != nil {
		t.Fatalf("request link: %v", err)
	}
	if _, err := svc.ConfirmByToken(ctx, tokenFromMail(t, mailer.lastBody)); err != nil {
		t.Fatalf("confirm by token: %v", err)
	}
	acc, err := store.GetByID(ctx, guest.ID)
	if err != nil {
		t.Fatalf("get: %v", err)
	}
	if acc.IsGuest {
		t.Error("linking an email via the deeplink must promote the guest to durable")
	}
}
