package mappers

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

	"github.com/google/uuid"
)

func AccountEntityToResponse(entity *entities.Account) *models.AccountResponse {
	response := &models.AccountResponse{
		ID:               entity.ID,
		OrganizationID:   entity.OrganizationID,
		OutletID:         entity.OutletID,
		ChartOfAccountID: entity.ChartOfAccountID,
		Name:             entity.Name,
		Number:           entity.Number,
		AccountType:      string(entity.AccountType),
		OpeningBalance:   entity.OpeningBalance,
		CurrentBalance:   entity.CurrentBalance,
		Description:      entity.Description,
		IsActive:         entity.IsActive,
		IsSystem:         entity.IsSystem,
		CreatedAt:        entity.CreatedAt,
		UpdatedAt:        entity.UpdatedAt,
	}

	if entity.ChartOfAccount.ID != uuid.Nil {
		response.ChartOfAccount = ChartOfAccountEntityToResponse(&entity.ChartOfAccount)
	}

	return response
}

func AccountCreateRequestToEntity(req *models.CreateAccountRequest, organizationID uuid.UUID, outletID *uuid.UUID) *entities.Account {
	return &entities.Account{
		OrganizationID:   organizationID,
		OutletID:         outletID,
		ChartOfAccountID: req.ChartOfAccountID,
		Name:             req.Name,
		Number:           req.Number,
		AccountType:      entities.AccountType(req.AccountType),
		OpeningBalance:   req.OpeningBalance,
		CurrentBalance:   req.OpeningBalance, // Initialize current balance with opening balance
		Description:      req.Description,
		IsActive:         true,
		IsSystem:         false,
	}
}

func AccountUpdateRequestToEntity(entity *entities.Account, req *models.UpdateAccountRequest) {
	if req.ChartOfAccountID != nil {
		entity.ChartOfAccountID = *req.ChartOfAccountID
	}
	if req.Name != nil {
		entity.Name = *req.Name
	}
	if req.Number != nil {
		entity.Number = *req.Number
	}
	if req.AccountType != nil {
		entity.AccountType = entities.AccountType(*req.AccountType)
	}
	if req.OpeningBalance != nil {
		entity.OpeningBalance = *req.OpeningBalance
	}
	if req.Description != nil {
		entity.Description = req.Description
	}
	if req.IsActive != nil {
		entity.IsActive = *req.IsActive
	}
}
