package service

import (
	"context"
	"kra/internal/biz/system"

	"kra/internal/service/dto"
)

type PositionService struct{ uc *system.PositionUsecase }

func NewPositionService(uc *system.PositionUsecase) *PositionService {
	return &PositionService{uc: uc}
}

func positionDomain(value *dto.PositionRequest) *system.Position {
	return &system.Position{ID: value.ID, Name: value.Name, Code: value.Code, Sort: value.Sort, Status: value.Status, Remark: value.Remark}
}

func positionResponse(value *system.Position) *dto.PositionResponse {
	return &dto.PositionResponse{ID: value.ID, CreatedAt: value.CreatedAt, UpdatedAt: value.UpdatedAt, DeletedAt: nil, Name: value.Name, Code: value.Code, Sort: value.Sort, Status: value.Status, Remark: value.Remark}
}

func (s *PositionService) Positions(ctx context.Context, req *dto.PositionListRequest) ([]*dto.PositionResponse, int64, error) {
	items, total, err := s.uc.Positions(ctx, req.Page, req.PageSize, &system.PositionListFilter{Name: req.Name, Code: req.Code, Status: req.Status})
	if err != nil {
		return nil, 0, err
	}
	out := make([]*dto.PositionResponse, 0, len(items))
	for _, item := range items {
		out = append(out, positionResponse(item))
	}
	return out, total, nil
}

func (s *PositionService) Create(ctx context.Context, req *dto.PositionRequest) error {
	return s.uc.CreatePosition(ctx, positionDomain(req))
}

func (s *PositionService) Update(ctx context.Context, req *dto.PositionRequest) error {
	return s.uc.UpdatePosition(ctx, positionDomain(req))
}

func (s *PositionService) Delete(ctx context.Context, id uint) error {
	return s.uc.DeletePosition(ctx, id)
}

func (s *PositionService) Position(ctx context.Context, id uint) (*dto.PositionResponse, error) {
	value, err := s.uc.Position(ctx, id)
	if err != nil {
		return nil, err
	}
	return positionResponse(value), nil
}

func (s *PositionService) UserIDs(ctx context.Context, id uint) ([]uint, error) {
	return s.uc.PositionUserIDs(ctx, id)
}

func (s *PositionService) SetUsers(ctx context.Context, req *dto.SetPositionUsersRequest) error {
	return s.uc.SetPositionUsers(ctx, req.PositionID, req.UserIDs)
}

func (s *PositionService) SetUserPositions(ctx context.Context, req *dto.SetUserPositionsRequest) error {
	return s.uc.SetUserPositions(ctx, req.ID, req.PositionIDs)
}
