package main

import (
	"fmt"
	"log"
	"time"

	"direct-dev.ru/gitea/GiteaAdmin/elowdb-go/pkg/linedb"
)

type User struct {
	ID      int    `json:"id"`
	Name    string `json:"name"`
	Email   string `json:"email"`
	Age     int    `json:"age"`
	Created string `json:"created"`
}

func main() {
	// Создаем опции инициализации
	initOptions := &linedb.LineDbInitOptions{
		CacheSize: 1000,
		CacheTTL:  5 * time.Minute,
		DBFolder:  "./examples/basic/data",
		Collections: []linedb.JSONLFileOptions{
			{
				CollectionName: "users",
				AllocSize:      512,
				IndexedFields:  []string{"id", "email", "name"},
				UniqueFields:   []string{"email"},
			},
		},
	}

	// Создаем базу данных
	db := linedb.NewLineDb(nil)

	// Инициализируем базу данных
	if err := db.Init(false, initOptions); err != nil {
		log.Fatalf("Failed to init database: %v", err)
	}
	defer db.Close()

	//delete all entries from users collection
	if _, err := db.Delete(map[string]any{}, "users", linedb.LineDbAdapterOptions{}); err != nil {
		log.Fatalf("Failed to delete users: %v", err)
	}

	fmt.Println("All entries deleted from users collection")

	// Создаем тестовых пользователей
	users := []any{
		map[string]any{
			"id":      1,
			"name":    "John Doe",
			"email":   "john@example.com",
			"age":     30,
			"created": time.Now().Format(time.RFC3339),
		},
		map[string]any{
			"id":      2,
			"name":    "Jane Smith",
			"email":   "jane@example.com",
			"age":     25,
			"created": time.Now().Format(time.RFC3339),
		},
		map[string]any{
			"id":      3,
			"name":    "Bob Johnson",
			"email":   "bob@example.com",
			"age":     35,
			"created": time.Now().Format(time.RFC3339),
		},
	}

	// Вставляем пользователей
	if err := db.Insert(users, "users", linedb.LineDbAdapterOptions{}); err != nil {
		log.Fatalf("Failed to insert users: %v", err)
	}

	fmt.Println("Users inserted successfully!")

	// Читаем всех пользователей
	allUsers, err := db.Read("users", linedb.LineDbAdapterOptions{})
	if err != nil {
		log.Fatalf("Failed to read users: %v", err)
	}

	fmt.Printf("Total users: %d\n", len(allUsers))
	for i, user := range allUsers {
		fmt.Printf("User %d: %+v\n", i+1, user)
	}

	// Ищем пользователя по email
	filter := map[string]any{"email": "john@example.com"}
	foundUsers, err := db.ReadByFilter(filter, "users", linedb.LineDbAdapterOptions{})
	if err != nil {
		log.Fatalf("Failed to filter users: %v", err)
	}

	fmt.Printf("Found %d users with email john@example.com\n", len(foundUsers))
	for _, user := range foundUsers {
		fmt.Printf("Found user: %+v\n", user)
	}

	// Обновляем пользователя
	updateData := map[string]any{"age": 31, "email": "jane@example.com"}
	updateFilter := map[string]any{"email": "john@example.com"}
	updatedUsers, err := db.Update(updateData, "users", updateFilter, linedb.LineDbAdapterOptions{})
	if err != nil {
		log.Printf("Failed to update user: %v", err)
	}

	updateData = map[string]any{"age": 31, "email": "john@example.com"}
	updateFilter = map[string]any{"email": "john@example.com"}
	updatedUsers, err = db.Update(updateData, "users", updateFilter, linedb.LineDbAdapterOptions{})
	if err != nil {
		log.Printf("Failed again to update user: %v", err)
	}

	fmt.Printf("Updated %d users\n", len(updatedUsers))

	// Удаляем пользователя
	deleteFilter := map[string]any{"email": "jane@example.com"}
	deletedUsers, err := db.Delete(deleteFilter, "users", linedb.LineDbAdapterOptions{})
	if err != nil {
		log.Fatalf("Failed to delete user: %v", err)
	}

	fmt.Printf("Deleted %d users\n", len(deletedUsers))

	// Читаем оставшихся пользователей
	remainingUsers, err := db.Read("users", linedb.LineDbAdapterOptions{})
	if err != nil {
		log.Fatalf("Failed to read remaining users: %v", err)
	}

	fmt.Printf("Remaining users: %d\n", len(remainingUsers))
	for i, user := range remainingUsers {
		fmt.Printf("Remaining user %d: %+v\n", i+1, user)
	}
}
