package main

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

// Issue 0089: tiempo maximo por columna.

func openTestDB(t *testing.T) *DB {
	t.Helper()
	dir := t.TempDir()
	path := filepath.Join(dir, "test.db")
	db, err := openDB(path)
	if err != nil {
		t.Fatalf("openDB: %v", err)
	}
	t.Cleanup(func() {
		db.Close()
		_ = os.Remove(path)
	})
	return db
}

func TestColumnMaxTimeMinutes_Defaults(t *testing.T) {
	db := openTestDB(t)

	c, err := db.CreateColumn("col1")
	if err != nil {
		t.Fatalf("CreateColumn: %v", err)
	}
	if c.MaxTimeMinutes != 0 {
		t.Fatalf("new column max_time_minutes = %d, want 0", c.MaxTimeMinutes)
	}

	cols, err := db.ListColumns()
	if err != nil {
		t.Fatalf("ListColumns: %v", err)
	}
	if len(cols) == 0 || cols[0].MaxTimeMinutes != 0 {
		t.Fatalf("listed col max_time_minutes = %d, want 0", cols[0].MaxTimeMinutes)
	}
}

func TestColumnMaxTimeMinutes_Update(t *testing.T) {
	db := openTestDB(t)

	c, _ := db.CreateColumn("c")
	v := 30
	if err := db.UpdateColumn(c.ID, ColumnPatch{MaxTimeMinutes: &v}); err != nil {
		t.Fatalf("UpdateColumn set 30: %v", err)
	}

	cols, _ := db.ListColumns()
	if cols[0].MaxTimeMinutes != 30 {
		t.Fatalf("after set max=30 got %d", cols[0].MaxTimeMinutes)
	}

	// Negative clamps to 0.
	neg := -5
	if err := db.UpdateColumn(c.ID, ColumnPatch{MaxTimeMinutes: &neg}); err != nil {
		t.Fatalf("UpdateColumn neg: %v", err)
	}
	cols, _ = db.ListColumns()
	if cols[0].MaxTimeMinutes != 0 {
		t.Fatalf("negative should clamp to 0, got %d", cols[0].MaxTimeMinutes)
	}

	// Other fields untouched.
	w := 555
	if err := db.UpdateColumn(c.ID, ColumnPatch{Width: &w}); err != nil {
		t.Fatalf("UpdateColumn width: %v", err)
	}
	cols, _ = db.ListColumns()
	if cols[0].MaxTimeMinutes != 0 {
		t.Fatalf("max_time should still be 0 after width update, got %d", cols[0].MaxTimeMinutes)
	}
	if cols[0].Width != 555 {
		t.Fatalf("width = %d, want 555", cols[0].Width)
	}
}
