package integration_test

import (
	"context"
	"testing"
	"time"

	"galaxy/integration/testenv"
	usermodel "galaxy/model/user"
	"galaxy/transcoder"
)

// TestUserSettingsUpdate verifies `user.settings.update` accepts a
// valid BCP 47 / IANA pair and rejects malformed inputs through the
// gateway authenticated edge surface.
func TestUserSettingsUpdate(t *testing.T) {
	plat := testenv.Bootstrap(t, testenv.BootstrapOptions{})
	ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
	defer cancel()

	sess := testenv.RegisterSession(t, plat, "pilot+settings@example.com")
	gw, err := sess.DialAuthenticated(ctx, plat)
	if err != nil {
		t.Fatalf("dial: %v", err)
	}
	defer gw.Close()

	good, err := transcoder.UpdateMySettingsRequestToPayload(&usermodel.UpdateMySettingsRequest{
		PreferredLanguage: "fr-CA",
		TimeZone:          "America/Toronto",
	})
	if err != nil {
		t.Fatalf("encode payload: %v", err)
	}
	res, err := gw.Execute(ctx, usermodel.MessageTypeUpdateMySettings, good, testenv.ExecuteOptions{})
	if err != nil {
		t.Fatalf("execute valid update: %v", err)
	}
	if res.ResultCode != "ok" {
		t.Fatalf("valid update result_code = %q, want ok", res.ResultCode)
	}
	updated, err := transcoder.PayloadToAccountResponse(res.PayloadBytes)
	if err != nil {
		t.Fatalf("decode response: %v", err)
	}
	if updated.Account.PreferredLanguage != "fr-CA" || updated.Account.TimeZone != "America/Toronto" {
		t.Fatalf("settings not applied: lang=%q tz=%q", updated.Account.PreferredLanguage, updated.Account.TimeZone)
	}

	bad, err := transcoder.UpdateMySettingsRequestToPayload(&usermodel.UpdateMySettingsRequest{
		PreferredLanguage: "not-a-language",
		TimeZone:          "Mars/Olympus",
	})
	if err != nil {
		t.Fatalf("encode bad payload: %v", err)
	}
	res, err = gw.Execute(ctx, usermodel.MessageTypeUpdateMySettings, bad, testenv.ExecuteOptions{})
	if err != nil {
		t.Fatalf("execute invalid update: %v", err)
	}
	if res.ResultCode == "ok" {
		t.Fatalf("invalid update was accepted: %q", res.ResultCode)
	}
}
