package service

import (
	"context"

	"kra/app/system/internal/biz"
)

type PositionService struct{ uc *biz.PositionUsecase }

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

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

func positionResponse(value *biz.Position) *PositionResponse {
	return &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 *PositionListRequest) ([]*PositionResponse, int64, error) {
	items, total, err := s.uc.Positions(ctx, req.Page, req.PageSize, &biz.PositionListFilter{Name: req.Name, Code: req.Code, Status: req.Status})
	if err != nil {
		return nil, 0, err
	}
	out := make([]*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 *PositionRequest) error {
	return s.uc.CreatePosition(ctx, positionDomain(req))
}

func (s *PositionService) Update(ctx context.Context, req *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) (*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 *SetPositionUsersRequest) error {
	return s.uc.SetPositionUsers(ctx, req.PositionID, req.UserIDs)
}

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