package dbsync

import (
	"context"
	"path/filepath"
	"testing"
)

func TestDropTableOnEndpoint(t *testing.T) {
	dir := t.TempDir()
	dsn := "file:" + filepath.ToSlash(filepath.Join(dir, "drop.db")) + "?_pragma=busy_timeout(5000)"
	db, err := Open(DriverSQLite, dsn)
	if err != nil {
		t.Fatal(err)
	}
	ctx := context.Background()
	if err := EnsureTableFromColumns(ctx, db, DriverSQLite, "模块·测2·item", "id", []string{"id", "before_day"}); err != nil {
		t.Fatal(err)
	}
	if err := EnsureMeta(ctx, db, DriverSQLite); err != nil {
		t.Fatal(err)
	}
	_ = UpsertMeta(ctx, db, DriverSQLite, "模块·测2·item", "pk1", 1)
	_ = db.Close()

	ep := Endpoint{Driver: DriverSQLite, DSN: dsn}
	res, err := DropTableOnEndpoint(ctx, ep, "remote", "模块·测2·item")
	if err != nil {
		t.Fatal(err)
	}
	if !res.OK || !res.Dropped {
		t.Fatalf("unexpected: %+v", res)
	}
	if res.MetaCleared < 1 {
		t.Fatalf("want meta cleared: %+v", res)
	}

	db2, err := Open(DriverSQLite, dsn)
	if err != nil {
		t.Fatal(err)
	}
	defer db2.Close()
	exists, err := tableExists(ctx, db2, DriverSQLite, "模块·测2·item")
	if err != nil || exists {
		t.Fatalf("table should be gone exists=%v err=%v", exists, err)
	}

	// idempotent
	res2, err := DropTableOnEndpoint(ctx, ep, "remote", "模块·测2·item")
	if err != nil || !res2.OK || res2.Dropped {
		t.Fatalf("idempotent: %+v err=%v", res2, err)
	}
	if _, err := DropTableOnEndpoint(ctx, ep, "remote", "_ajz_sync_meta"); err == nil {
		t.Fatal("expected reject system table")
	}
}
