package sqlite

import (
	"os"
	"path/filepath"
	"testing"

	"github.com/glebarez/sqlite"
	"github.com/rose_cat707/luminary/internal/model"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

func TestPreMigrateIPRulesTable_LegacySchema(t *testing.T) {
	dir := t.TempDir()
	path := filepath.Join(dir, "legacy.db")

	legacy, err := gorm.Open(sqlite.Open(path), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
	if err != nil {
		t.Fatal(err)
	}
	if err := legacy.Exec(`
		CREATE TABLE ip_rules (
			id INTEGER PRIMARY KEY AUTOINCREMENT,
			c_id_r TEXT NOT NULL,
			type TEXT NOT NULL,
			scope TEXT NOT NULL DEFAULT 'all',
			enabled NUMERIC DEFAULT 1,
			created_at DATETIME
		);
		INSERT INTO ip_rules (c_id_r, type, scope, enabled) VALUES ('10.0.0.1', 'allow', 'proxy', 1);
	`).Error; err != nil {
		t.Fatal(err)
	}
	sqlDB, _ := legacy.DB()
	sqlDB.Close()

	store, err := New(path)
	if err != nil {
		t.Fatalf("New() with legacy schema: %v", err)
	}

	var rules []model.IPRule
	if err := store.DB().Find(&rules).Error; err != nil {
		t.Fatal(err)
	}
	if len(rules) != 1 || rules[0].CIDR != "10.0.0.1" {
		t.Fatalf("unexpected rules: %+v", rules)
	}
	if store.DB().Migrator().HasColumn(&model.IPRule{}, "c_id_r") {
		t.Fatal("legacy c_id_r column should be removed")
	}
	if tableHasColumn(store.DB(), "ip_rules", "c_id_r") {
		t.Fatal("legacy c_id_r column should be removed")
	}
}

func TestNew_FreshDatabase(t *testing.T) {
	dir := t.TempDir()
	path := filepath.Join(dir, "fresh.db")
	store, err := New(path)
	if err != nil {
		t.Fatal(err)
	}
	if err := store.DB().Create(&model.IPRule{CIDR: "127.0.0.1", Type: model.IPRuleAllow, Scope: model.IPScopeProxy, Enabled: true}).Error; err != nil {
		t.Fatal(err)
	}
	_ = os.Remove(path)
}
