//go:build integration

package inttest

import (
	"context"
	"errors"
	"strings"
	"testing"

	"github.com/google/uuid"

	"scrabble/backend/internal/account"
	"scrabble/backend/internal/feedback"
)

func newFeedbackService() *feedback.Service {
	return feedback.NewService(feedback.NewStore(testDB), account.NewStore(testDB))
}

// latestFeedbackID returns the id of the account's single message (across states).
func latestFeedbackID(t *testing.T, svc *feedback.Service, acc uuid.UUID) uuid.UUID {
	t.Helper()
	ctx := context.Background()
	for _, status := range []string{"unread", "read", "archived"} {
		rows, err := svc.AdminList(ctx, feedback.AdminFilter{AccountID: acc, Status: status}, 50, 0)
		if err != nil {
			t.Fatalf("admin list %s: %v", status, err)
		}
		if len(rows) > 0 {
			return rows[0].ID
		}
	}
	t.Fatal("no feedback message for account")
	return uuid.Nil
}

func TestFeedbackGuestRejected(t *testing.T) {
	svc := newFeedbackService()
	guest := provisionGuest(t)
	if err := svc.Submit(context.Background(), guest, "hi", nil, "", "web", "v1", "+05:00", "1.2.3.4"); !errors.Is(err, feedback.ErrGuestForbidden) {
		t.Fatalf("guest submit err = %v, want ErrGuestForbidden", err)
	}
}

func TestFeedbackSubmitGateAndReplyLifecycle(t *testing.T) {
	ctx := context.Background()
	svc := newFeedbackService()
	acc := provisionAccount(t)

	if err := svc.Submit(ctx, acc, "  please fix the board  ", []byte("PNGDATA"), "shot.png", "ios", "v1.2.0", "+03:00", "9.9.9.9"); err != nil {
		t.Fatalf("submit: %v", err)
	}
	// Anti-spam gate: a second message is refused while the first is unreviewed.
	if err := svc.Submit(ctx, acc, "again", nil, "", "web", "", "", ""); !errors.Is(err, feedback.ErrPendingReview) {
		t.Fatalf("second submit err = %v, want ErrPendingReview", err)
	}
	if st, err := svc.State(ctx, acc); err != nil {
		t.Fatal(err)
	} else if st.CanSend || st.BlockedReason != "pending" || st.Reply != nil {
		t.Fatalf("state = %+v, want pending / no reply", st)
	}

	id := latestFeedbackID(t, svc, acc)
	m, err := svc.AdminGet(ctx, id)
	if err != nil {
		t.Fatalf("admin get: %v", err)
	}
	if m.Body != "please fix the board" { // trimmed
		t.Fatalf("body = %q, want trimmed", m.Body)
	}
	if !m.HasAttachment || m.AttachmentName != "shot.png" || m.Channel != "ios" || m.SenderIP != "9.9.9.9" || m.Version != "v1.2.0" || m.BrowserTZ != "+03:00" {
		t.Fatalf("admin message = %+v", m)
	}
	if name, data, ok, err := svc.Attachment(ctx, id); err != nil || !ok || name != "shot.png" || string(data) != "PNGDATA" {
		t.Fatalf("attachment = (%q, %q, %v, %v)", name, data, ok, err)
	}

	// Reply: marks the message read (so the player can send again) and is undelivered.
	if err := svc.Reply(ctx, id, "We are on it."); err != nil {
		t.Fatalf("reply: %v", err)
	}
	if unread, err := svc.ReplyUnread(ctx, acc); err != nil || !unread {
		t.Fatalf("reply unread = %v (err %v), want true", unread, err)
	}
	st, err := svc.State(ctx, acc)
	if err != nil {
		t.Fatal(err)
	}
	if !st.CanSend {
		t.Fatal("want canSend true after the message was read via reply")
	}
	if st.Reply == nil || st.Reply.Body != "We are on it." {
		t.Fatalf("reply not shown: %+v", st.Reply)
	}
	// Fetching the state delivered the reply: the badge clears.
	if unread, err := svc.ReplyUnread(ctx, acc); err != nil || unread {
		t.Fatalf("reply unread = %v (err %v), want false after State", unread, err)
	}

	// The reply is hidden one week after it was delivered.
	if _, err := testDB.ExecContext(ctx,
		`UPDATE backend.feedback_messages SET reply_read_at = now() - interval '8 days' WHERE message_id = $1`, id); err != nil {
		t.Fatalf("age reply: %v", err)
	}
	if st, err := svc.State(ctx, acc); err != nil {
		t.Fatal(err)
	} else if st.Reply != nil {
		t.Fatalf("reply should be hidden after a week, got %+v", st.Reply)
	}
}

func TestFeedbackReplyHiddenAfterNewMessage(t *testing.T) {
	ctx := context.Background()
	svc := newFeedbackService()
	acc := provisionAccount(t)

	// msg1, replied → the player can send again and currently sees the reply.
	if err := svc.Submit(ctx, acc, "first", nil, "", "web", "", "", ""); err != nil {
		t.Fatalf("submit msg1: %v", err)
	}
	if err := svc.Reply(ctx, latestFeedbackID(t, svc, acc), "the answer"); err != nil {
		t.Fatalf("reply: %v", err)
	}
	if st, err := svc.State(ctx, acc); err != nil {
		t.Fatal(err)
	} else if st.Reply == nil || st.Reply.Body != "the answer" {
		t.Fatalf("reply not shown before the new message: %+v", st.Reply)
	}

	// Sending a new message immediately drops the previous reply (it now belongs to an
	// older message), even though it is well within the one-week window.
	if err := svc.Submit(ctx, acc, "second", nil, "", "web", "", "", ""); err != nil {
		t.Fatalf("submit msg2: %v", err)
	}
	st, err := svc.State(ctx, acc)
	if err != nil {
		t.Fatal(err)
	}
	if st.Reply != nil {
		t.Fatalf("reply should be hidden after a new message, got %+v", st.Reply)
	}
	if st.CanSend || st.BlockedReason != "pending" {
		t.Fatalf("state after new message = %+v, want pending", st)
	}
}

func TestFeedbackSnapshotsLanguage(t *testing.T) {
	ctx := context.Background()
	svc := newFeedbackService()
	acc := provisionAccount(t)
	if _, err := testDB.ExecContext(ctx,
		`UPDATE backend.accounts SET preferred_language = 'en' WHERE account_id = $1`, acc); err != nil {
		t.Fatalf("set language: %v", err)
	}
	// A message snapshots the sender's interface language at submit time.
	if err := svc.Submit(ctx, acc, "from telegram", nil, "", "telegram", "", "", ""); err != nil {
		t.Fatalf("submit: %v", err)
	}
	id := latestFeedbackID(t, svc, acc)
	if m, err := svc.AdminGet(ctx, id); err != nil {
		t.Fatalf("admin get: %v", err)
	} else if m.Lang != "en" {
		t.Fatalf("snapshot = lang %q, want en", m.Lang)
	}
	// Changing the account afterwards must not change the stored snapshot.
	if _, err := testDB.ExecContext(ctx,
		`UPDATE backend.accounts SET preferred_language = 'ru' WHERE account_id = $1`, acc); err != nil {
		t.Fatalf("change language: %v", err)
	}
	if m, err := svc.AdminGet(ctx, id); err != nil {
		t.Fatal(err)
	} else if m.Lang != "en" {
		t.Fatalf("snapshot drifted after account change = lang %q, want en", m.Lang)
	}
}

func TestFeedbackBanRole(t *testing.T) {
	ctx := context.Background()
	svc := newFeedbackService()
	accounts := account.NewStore(testDB)
	acc := provisionAccount(t)

	if err := accounts.GrantRole(ctx, acc, account.RoleFeedbackBanned); err != nil {
		t.Fatalf("grant role: %v", err)
	}
	if err := svc.Submit(ctx, acc, "hi", nil, "", "web", "", "", ""); !errors.Is(err, feedback.ErrBanned) {
		t.Fatalf("banned submit err = %v, want ErrBanned", err)
	}
	if st, err := svc.State(ctx, acc); err != nil {
		t.Fatal(err)
	} else if st.CanSend || st.BlockedReason != "banned" {
		t.Fatalf("state = %+v, want banned", st)
	}
	// Revoke restores submission (the /users unblock path).
	if err := accounts.RevokeRole(ctx, acc, account.RoleFeedbackBanned); err != nil {
		t.Fatalf("revoke role: %v", err)
	}
	if err := svc.Submit(ctx, acc, "hi again", nil, "", "web", "", "", ""); err != nil {
		t.Fatalf("submit after unban: %v", err)
	}
}

func TestFeedbackValidation(t *testing.T) {
	ctx := context.Background()
	svc := newFeedbackService()
	tests := []struct {
		name           string
		body           string
		attachment     []byte
		attachmentName string
		want           error
	}{
		{"empty body", "   ", nil, "", feedback.ErrEmptyMessage},
		{"too long", strings.Repeat("a", 1025), nil, "", feedback.ErrMessageTooLong},
		{"bad type", "ok", []byte("x"), "evil.exe", feedback.ErrAttachmentType},
		{"too large", "ok", make([]byte, 1_000_001), "a.png", feedback.ErrAttachmentTooLarge},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			acc := provisionAccount(t) // fresh account so the pending gate never fires first
			if err := svc.Submit(ctx, acc, tt.body, tt.attachment, tt.attachmentName, "web", "", "", ""); !errors.Is(err, tt.want) {
				t.Fatalf("submit err = %v, want %v", err, tt.want)
			}
		})
	}
}

func TestFeedbackAdminLifecycle(t *testing.T) {
	ctx := context.Background()
	svc := newFeedbackService()
	acc := provisionAccount(t)

	if err := svc.Submit(ctx, acc, "first report", nil, "", "web", "", "", ""); err != nil {
		t.Fatalf("submit: %v", err)
	}
	id := latestFeedbackID(t, svc, acc)

	inCount := func(status string) int {
		t.Helper()
		n, err := svc.AdminCount(ctx, feedback.AdminFilter{AccountID: acc, Status: status})
		if err != nil {
			t.Fatalf("count %s: %v", status, err)
		}
		return n
	}

	if inCount("unread") != 1 || inCount("read") != 0 || inCount("archived") != 0 {
		t.Fatalf("after submit: unread=%d read=%d archived=%d", inCount("unread"), inCount("read"), inCount("archived"))
	}
	// Marking read moves it from the unread queue to the read list.
	if err := svc.MarkRead(ctx, id); err != nil {
		t.Fatalf("mark read: %v", err)
	}
	if inCount("unread") != 0 || inCount("read") != 1 {
		t.Fatalf("after read: unread=%d read=%d", inCount("unread"), inCount("read"))
	}
	// Archiving moves it to the archive.
	if err := svc.Archive(ctx, id); err != nil {
		t.Fatalf("archive: %v", err)
	}
	if inCount("read") != 0 || inCount("archived") != 1 {
		t.Fatalf("after archive: read=%d archived=%d", inCount("read"), inCount("archived"))
	}
	// Deleting removes it entirely.
	if err := svc.Delete(ctx, id); err != nil {
		t.Fatalf("delete: %v", err)
	}
	if inCount("archived") != 0 {
		t.Fatalf("after delete: archived=%d, want 0", inCount("archived"))
	}
}

func TestFeedbackDeleteAllByAccount(t *testing.T) {
	ctx := context.Background()
	svc := newFeedbackService()
	acc := provisionAccount(t)

	if err := svc.Submit(ctx, acc, "one", nil, "", "web", "", "", ""); err != nil {
		t.Fatalf("submit: %v", err)
	}
	if err := svc.DeleteAllByAccount(ctx, acc); err != nil {
		t.Fatalf("delete all: %v", err)
	}
	// The pending gate is clear again (no messages left), so the account can submit.
	if has, err := svc.ReplyUnread(ctx, acc); err != nil || has {
		t.Fatalf("reply unread after delete-all = %v (err %v)", has, err)
	}
	if err := svc.Submit(ctx, acc, "fresh", nil, "", "web", "", "", ""); err != nil {
		t.Fatalf("submit after delete-all: %v", err)
	}
}
