package playground

import (
	"context"
	"strings"
	"testing"

	"code.patial.tech/go/pgm/playground/db"
	"code.patial.tech/go/pgm/playground/db/user"
)

func TestUpdateQuery(t *testing.T) {
	got := db.User.Update().
		Set(user.FirstName, "ankit").
		Set(user.MiddleName, "singh").
		Set(user.LastName, "patial").
		Where(
			user.Email.Eq("aa@aa.com"),
		).
		Where(
			user.StatusID.NotEq(1),
		).
		String()

	expected := "UPDATE users SET first_name=$1, middle_name=$2, last_name=$3 WHERE users.email = $4 AND users.status_id != $5"
	if got != expected {
		t.Errorf("\nexpected: %q\ngot: %q", expected, got)
	}
}

func TestUpdateQueryValidation(t *testing.T) {
	// Test that UPDATE without Set() returns error
	err := db.User.Update().
		Where(user.Email.Eq("aa@aa.com")).
		Exec(context.Background())

	if err == nil {
		t.Error("Expected error when calling Exec() without Set(), got nil")
	}

	if !strings.Contains(err.Error(), "no columns to update") {
		t.Errorf("Expected error message to contain 'no columns to update', got: %v", err)
	}
}

// BenchmarkUpdateQuery-12    	 2334889	       503.6 ns/op	    1112 B/op	      17 allocs/op
func BenchmarkUpdateQuery(b *testing.B) {
	for b.Loop() {
		_ = db.User.Update().
			Set(user.FirstName, "ankit").
			Set(user.MiddleName, "singh").
			Set(user.LastName, "patial").
			Where(
				user.Email.Eq("aa@aa.com"),
			).
			Where(
				user.StatusID.NotEq(1),
			).
			String()
	}
}
