package service

import (
	"context"

	"eslogad-be/internal/contract"
	"eslogad-be/internal/entities"
	"eslogad-be/internal/repository"
	"eslogad-be/internal/transformer"

	"github.com/google/uuid"
)

type DispositionRouteServiceImpl struct {
	repo *repository.DispositionRouteRepository
}

func NewDispositionRouteService(repo *repository.DispositionRouteRepository) *DispositionRouteServiceImpl {
	return &DispositionRouteServiceImpl{repo: repo}
}

func (s *DispositionRouteServiceImpl) Create(ctx context.Context, req *contract.CreateDispositionRouteRequest) (*contract.DispositionRouteResponse, error) {
	entity := &entities.DispositionRoute{FromDepartmentID: req.FromDepartmentID, ToDepartmentID: req.ToDepartmentID}
	if req.IsActive != nil {
		entity.IsActive = *req.IsActive
	}
	if req.AllowedActions != nil {
		entity.AllowedActions = entities.JSONB(*req.AllowedActions)
	}
	if err := s.repo.Create(ctx, entity); err != nil {
		return nil, err
	}
	resp := transformer.DispositionRoutesToContract([]entities.DispositionRoute{*entity})[0]
	return &resp, nil
}
func (s *DispositionRouteServiceImpl) Update(ctx context.Context, id uuid.UUID, req *contract.UpdateDispositionRouteRequest) (*contract.DispositionRouteResponse, error) {
	entity, err := s.repo.Get(ctx, id)
	if err != nil {
		return nil, err
	}
	if req.IsActive != nil {
		entity.IsActive = *req.IsActive
	}
	if req.AllowedActions != nil {
		entity.AllowedActions = entities.JSONB(*req.AllowedActions)
	}
	if err := s.repo.Update(ctx, entity); err != nil {
		return nil, err
	}
	resp := transformer.DispositionRoutesToContract([]entities.DispositionRoute{*entity})[0]
	return &resp, nil
}
func (s *DispositionRouteServiceImpl) Get(ctx context.Context, id uuid.UUID) (*contract.DispositionRouteResponse, error) {
	entity, err := s.repo.Get(ctx, id)
	if err != nil {
		return nil, err
	}
	resp := transformer.DispositionRoutesToContract([]entities.DispositionRoute{*entity})[0]
	return &resp, nil
}
func (s *DispositionRouteServiceImpl) ListByFromDept(ctx context.Context, from uuid.UUID) (*contract.ListDispositionRoutesResponse, error) {
	list, err := s.repo.ListByFromDept(ctx, from)
	if err != nil {
		return nil, err
	}
	return &contract.ListDispositionRoutesResponse{Routes: transformer.DispositionRoutesToContract(list)}, nil
}
func (s *DispositionRouteServiceImpl) SetActive(ctx context.Context, id uuid.UUID, active bool) error {
	return s.repo.SetActive(ctx, id, active)
}
