package transformer

import (
	"eslogad-be/internal/contract"
	"eslogad-be/internal/entities"
)

func CreateUserRequestToEntity(req *contract.CreateUserRequest, passwordHash string) *entities.User {
	if req == nil {
		return nil
	}
	return &entities.User{
		Username:     req.Email,
		Name:         req.Name,
		Email:        req.Email,
		PasswordHash: passwordHash,
		IsActive:     true,
	}
}

func UpdateUserEntity(existing *entities.User, req *contract.UpdateUserRequest) *entities.User {
	if existing == nil || req == nil {
		return existing
	}
	if req.Name != nil {
		existing.Name = *req.Name
	}
	if req.Email != nil {
		existing.Email = *req.Email
		existing.Username = *req.Email
	}
	if req.IsActive != nil {
		existing.IsActive = *req.IsActive
	}
	return existing
}

func EntityToContract(user *entities.User) *contract.UserResponse {
	if user == nil {
		return nil
	}

	resp := &contract.UserResponse{
		ID:        user.ID,
		Username:  user.Username,
		Name:      user.Name,
		Email:     user.Email,
		IsActive:  user.IsActive,
		CreatedAt: user.CreatedAt,
		UpdatedAt: user.UpdatedAt,
	}
	if user.Profile != nil {
		resp.Profile = ProfileEntityToContract(user.Profile)
	}
	if user.Departments != nil && len(user.Departments) > 0 {
		resp.DepartmentResponse = DepartmentsToContract(user.Departments)
	}
	return resp
}

func EntitiesToContracts(users []*entities.User) []contract.UserResponse {
	if users == nil {
		return nil
	}
	responses := make([]contract.UserResponse, len(users))
	for i, u := range users {
		resp := EntityToContract(u)
		if resp != nil {
			responses[i] = *resp
		}
	}
	return responses
}
