package services

import (
	"errors"
	"path/filepath"
	"testing"

	"git.mchus.pro/mchus/quoteforge/internal/localdb"
)

func TestProjectServiceCreateRejectsReservedMainVariant(t *testing.T) {
	local, err := newProjectTestLocalDB(t)
	if err != nil {
		t.Fatalf("open localdb: %v", err)
	}
	service := NewProjectService(local)

	_, err = service.Create("tester", &CreateProjectRequest{
		Code:    "OPS-1",
		Variant: "main",
	})
	if !errors.Is(err, ErrReservedMainVariant) {
		t.Fatalf("expected ErrReservedMainVariant, got %v", err)
	}
}

func TestProjectServiceUpdateRejectsReservedMainVariant(t *testing.T) {
	local, err := newProjectTestLocalDB(t)
	if err != nil {
		t.Fatalf("open localdb: %v", err)
	}
	service := NewProjectService(local)

	created, err := service.Create("tester", &CreateProjectRequest{
		Code:    "OPS-1",
		Variant: "Lenovo",
	})
	if err != nil {
		t.Fatalf("create project: %v", err)
	}

	mainName := "main"
	_, err = service.Update(created.UUID, "tester", &UpdateProjectRequest{
		Variant: &mainName,
	})
	if !errors.Is(err, ErrReservedMainVariant) {
		t.Fatalf("expected ErrReservedMainVariant, got %v", err)
	}
}

func newProjectTestLocalDB(t *testing.T) (*localdb.LocalDB, error) {
	t.Helper()
	dbPath := filepath.Join(t.TempDir(), "project_test.db")
	local, err := localdb.New(dbPath)
	if err != nil {
		return nil, err
	}
	t.Cleanup(func() { _ = local.Close() })
	return local, nil
}
