package mappers

import (
	"apskel-pos-be/internal/entities"
	"apskel-pos-be/internal/models"

	"github.com/google/uuid"
)

func ChartOfAccountEntityToResponse(entity *entities.ChartOfAccount) *models.ChartOfAccountResponse {
	response := &models.ChartOfAccountResponse{
		ID:                   entity.ID,
		OrganizationID:       entity.OrganizationID,
		OutletID:             entity.OutletID,
		ChartOfAccountTypeID: entity.ChartOfAccountTypeID,
		ParentID:             entity.ParentID,
		Name:                 entity.Name,
		Code:                 entity.Code,
		Description:          entity.Description,
		IsActive:             entity.IsActive,
		IsSystem:             entity.IsSystem,
		CreatedAt:            entity.CreatedAt,
		UpdatedAt:            entity.UpdatedAt,
	}

	if entity.ChartOfAccountType.ID != uuid.Nil {
		response.ChartOfAccountType = ChartOfAccountTypeEntityToResponse(&entity.ChartOfAccountType)
	}

	if entity.Parent != nil {
		response.Parent = ChartOfAccountEntityToResponse(entity.Parent)
	}

	if len(entity.Children) > 0 {
		response.Children = make([]models.ChartOfAccountResponse, len(entity.Children))
		for i, child := range entity.Children {
			response.Children[i] = *ChartOfAccountEntityToResponse(&child)
		}
	}

	return response
}

func ChartOfAccountCreateRequestToEntity(req *models.CreateChartOfAccountRequest, organizationID uuid.UUID, outletID *uuid.UUID) *entities.ChartOfAccount {
	return &entities.ChartOfAccount{
		OrganizationID:       organizationID,
		OutletID:             outletID,
		ChartOfAccountTypeID: req.ChartOfAccountTypeID,
		ParentID:             req.ParentID,
		Name:                 req.Name,
		Code:                 req.Code,
		Description:          req.Description,
		IsActive:             true,
		IsSystem:             false,
	}
}

func ChartOfAccountUpdateRequestToEntity(entity *entities.ChartOfAccount, req *models.UpdateChartOfAccountRequest) {
	if req.ChartOfAccountTypeID != nil {
		entity.ChartOfAccountTypeID = *req.ChartOfAccountTypeID
	}
	if req.ParentID != nil {
		entity.ParentID = req.ParentID
	}
	if req.Name != nil {
		entity.Name = *req.Name
	}
	if req.Code != nil {
		entity.Code = *req.Code
	}
	if req.Description != nil {
		entity.Description = req.Description
	}
	if req.IsActive != nil {
		entity.IsActive = *req.IsActive
	}
}
