package entity_test

import (
	"testing"
	"time"

	"github.com/rede5/gohorsejobs/backend/internal/core/domain/entity"
)

func TestNewUser(t *testing.T) {
	u := entity.NewUser("u1", "t1", "John", "john@example.com")

	if u.ID != "u1" {
		t.Errorf("Expected ID u1, got %s", u.ID)
	}
	if u.Status != entity.UserStatusActive {
		t.Errorf("Expected Active status, got %s", u.Status)
	}
	if len(u.Roles) != 0 {
		t.Error("Expected 0 roles initialy")
	}
}

func TestUser_AssignRole_And_HasPermission(t *testing.T) {
	u := entity.NewUser("u1", "t1", "John", "john@example.com")

	perm := entity.Permission{Code: "TEST_PERM", Description: "Test"}
	role := entity.Role{Name: "TEST_ROLE", Permissions: []entity.Permission{perm}}

	u.AssignRole(role)

	if len(u.Roles) != 1 {
		t.Errorf("Expected 1 role, got %d", len(u.Roles))
	}

	if !u.HasPermission("TEST_PERM") {
		t.Error("Expected user to have TEST_PERM")
	}
	if u.HasPermission("INVALID_PERM") {
		t.Error("Expected user NOT to have INVALID_PERM")
	}
}

func TestNewCompany(t *testing.T) {
	doc := "123"
	c := entity.NewCompany("c1", "Acme", &doc, nil)

	if c.ID != "c1" {
		t.Errorf("Expected ID c1, got %s", c.ID)
	}
	if c.Status != "ACTIVE" {
		t.Errorf("Expected status ACTIVE, got %s", c.Status)
	}
}

func TestCompany_ActivateDeactivate(t *testing.T) {
	c := entity.NewCompany("c1", "Acme", nil, nil)

	time.Sleep(1 * time.Millisecond) // Ensure time moves for UpdatedAt check
	before := c.UpdatedAt

	c.Deactivate()
	if c.Status != "INACTIVE" {
		t.Error("Expected INACTIVE")
	}
	if !c.UpdatedAt.After(before) {
		t.Error("Expected UpdatedAt to update")
	}

	time.Sleep(1 * time.Millisecond)
	before = c.UpdatedAt
	c.Activate()
	if c.Status != "ACTIVE" {
		t.Error("Expected ACTIVE")
	}
	if !c.UpdatedAt.After(before) {
		t.Error("Expected UpdatedAt to update")
	}
}
