package service

import (
	"context"

	"apskel-pos-be/internal/contract"
	"apskel-pos-be/internal/mappers"
	"apskel-pos-be/internal/processor"

	"github.com/google/uuid"
)

type ChartOfAccountTypeService interface {
	contract.ChartOfAccountTypeContract
}

type ChartOfAccountTypeServiceImpl struct {
	processor processor.ChartOfAccountTypeProcessor
}

func NewChartOfAccountTypeService(processor processor.ChartOfAccountTypeProcessor) ChartOfAccountTypeService {
	return &ChartOfAccountTypeServiceImpl{
		processor: processor,
	}
}

func (s *ChartOfAccountTypeServiceImpl) CreateChartOfAccountType(ctx context.Context, req *contract.CreateChartOfAccountTypeRequest) (*contract.ChartOfAccountTypeResponse, error) {
	modelReq := mappers.ContractToModelCreateChartOfAccountTypeRequest(req)
	modelResp, err := s.processor.CreateChartOfAccountType(ctx, modelReq)
	if err != nil {
		return nil, err
	}
	return mappers.ModelToContractChartOfAccountTypeResponse(modelResp), nil
}

func (s *ChartOfAccountTypeServiceImpl) GetChartOfAccountTypeByID(ctx context.Context, id uuid.UUID) (*contract.ChartOfAccountTypeResponse, error) {
	modelResp, err := s.processor.GetChartOfAccountTypeByID(ctx, id)
	if err != nil {
		return nil, err
	}
	return mappers.ModelToContractChartOfAccountTypeResponse(modelResp), nil
}

func (s *ChartOfAccountTypeServiceImpl) UpdateChartOfAccountType(ctx context.Context, id uuid.UUID, req *contract.UpdateChartOfAccountTypeRequest) (*contract.ChartOfAccountTypeResponse, error) {
	modelReq := mappers.ContractToModelUpdateChartOfAccountTypeRequest(req)
	modelResp, err := s.processor.UpdateChartOfAccountType(ctx, id, modelReq)
	if err != nil {
		return nil, err
	}
	return mappers.ModelToContractChartOfAccountTypeResponse(modelResp), nil
}

func (s *ChartOfAccountTypeServiceImpl) DeleteChartOfAccountType(ctx context.Context, id uuid.UUID) error {
	return s.processor.DeleteChartOfAccountType(ctx, id)
}

func (s *ChartOfAccountTypeServiceImpl) ListChartOfAccountTypes(ctx context.Context, filters map[string]interface{}, page, limit int) ([]contract.ChartOfAccountTypeResponse, int, error) {
	modelResp, total, err := s.processor.ListChartOfAccountTypes(ctx, filters, page, limit)
	if err != nil {
		return nil, 0, err
	}
	
	contractResp := make([]contract.ChartOfAccountTypeResponse, len(modelResp))
	for i, resp := range modelResp {
		contractResp[i] = *mappers.ModelToContractChartOfAccountTypeResponse(&resp)
	}
	
	return contractResp, total, nil
}
