package service

import (
	"context"

	"kra/internal/biz"
	"kra/internal/service/dto"
)

type userInput struct {
	ID                                                    uint
	Username, Password, NickName, HeaderImg, Phone, Email string
	AuthorityID                                           uint
	Enable                                                int
	AuthorityIDs                                          []uint
}

type UserService struct {
	uc       *biz.UserUsecase
	settings *SecurityService
}

func NewUserService(uc *biz.UserUsecase, settings *SecurityService) *UserService {
	return &UserService{uc: uc, settings: settings}
}

func userRequestInput(value *dto.UserRequest) userInput {
	return userInput{ID: value.ID, Username: value.Username, Password: value.Password, NickName: value.NickName, HeaderImg: value.HeaderImg, AuthorityID: value.AuthorityID, AuthorityIDs: value.AuthorityIDs, Enable: value.Enable, Phone: value.Phone, Email: value.Email}
}
func (s *UserService) ListUsersRequest(ctx context.Context, value *dto.UserListRequest) ([]*dto.UserResponse, int64, error) {
	return s.ListUsers(ctx, value.Page, value.PageSize, &biz.UserListFilter{Username: value.Username, NickName: value.NickName, Phone: value.Phone, Email: value.Email, OrderKey: value.OrderKey, Desc: value.Desc})
}
func (s *UserService) CreateUserRequest(ctx context.Context, value *dto.UserRequest) (*dto.UserResponse, error) {
	return s.createUser(ctx, userRequestInput(value))
}
func (s *UserService) UpdateUserRequest(ctx context.Context, value *dto.UserRequest) error {
	return s.updateUser(ctx, userRequestInput(value))
}
func (s *UserService) UpdateSelfUserRequest(ctx context.Context, id uint, value *dto.SelfUserRequest) error {
	return s.updateSelfUser(ctx, userInput{ID: id, NickName: value.NickName, HeaderImg: value.HeaderImg, Phone: value.Phone, Email: value.Email, Enable: value.Enable})
}

func (s *UserService) User(ctx context.Context, id uint) (*dto.UserResponse, error) {
	value, err := s.uc.User(ctx, id)
	if err != nil {
		return nil, err
	}
	return convertUser(value), nil
}

func (s *UserService) UserByUUID(ctx context.Context, uuid string) (*dto.UserResponse, error) {
	value, err := s.uc.UserByUUID(ctx, uuid)
	if err != nil {
		return nil, err
	}
	return convertUser(value), nil
}

func (s *UserService) Menus(ctx context.Context, authorityID uint) ([]*dto.DynamicMenuResponse, error) {
	menus, err := s.uc.Menus(ctx, authorityID)
	if err != nil {
		return nil, err
	}
	return dynamicMenuResponses(menus), nil
}

func (s *UserService) ListUsers(ctx context.Context, page, pageSize int, filter *biz.UserListFilter) ([]*dto.UserResponse, int64, error) {
	users, total, err := s.uc.ListUsers(ctx, page, pageSize, filter)
	if err != nil {
		return nil, 0, err
	}
	result := make([]*dto.UserResponse, 0, len(users))
	for _, user := range users {
		result = append(result, convertUser(user))
	}
	return result, total, nil
}

func (s *UserService) Authorities(ctx context.Context) ([]*dto.AuthorityResponse, error) {
	values, err := s.uc.Authorities(ctx)
	if err != nil {
		return nil, err
	}
	result := make([]*dto.AuthorityResponse, 0, len(values))
	for _, value := range values {
		result = append(result, convertAuthority(*value))
	}
	return result, nil
}

func (s *UserService) createUser(ctx context.Context, input userInput) (*dto.UserResponse, error) {
	if err := s.settings.ValidatePassword(ctx, input.Password); err != nil {
		return nil, err
	}
	security, _ := s.settings.CurrentSecurity(ctx)
	mustChange := security != nil && security.ForceNewUserChangePassword
	user, err := s.uc.CreateUser(ctx, &biz.User{Username: input.Username, Password: input.Password, NickName: input.NickName, HeaderImg: input.HeaderImg, AuthorityID: input.AuthorityID, Phone: input.Phone, Email: input.Email, Enable: input.Enable, MustChangePassword: mustChange}, input.AuthorityIDs)
	if err != nil {
		return nil, err
	}
	return convertUser(user), nil
}
func (s *UserService) updateUser(ctx context.Context, input userInput) error {
	// The compatible ChangeUserInfo payload uses authorityIds for role assignment; the
	// standalone authorityId field is not applied by setUserInfo.
	return s.uc.UpdateUser(ctx, &biz.User{ID: input.ID, NickName: input.NickName, HeaderImg: input.HeaderImg, Phone: input.Phone, Email: input.Email, Enable: input.Enable}, input.AuthorityIDs)
}
func (s *UserService) updateSelfUser(ctx context.Context, input userInput) error {
	return s.uc.UpdateSelfUser(ctx, &biz.User{ID: input.ID, NickName: input.NickName, HeaderImg: input.HeaderImg, Phone: input.Phone, Email: input.Email, Enable: input.Enable})
}
func (s *UserService) DeleteUser(ctx context.Context, id uint) error {
	return s.uc.DeleteUser(ctx, id)
}
func (s *UserService) ResetPassword(ctx context.Context, id uint, password string) error {
	if err := s.settings.ValidatePassword(ctx, password); err != nil {
		return err
	}
	return s.uc.ResetPassword(ctx, id, password)
}
func (s *UserService) ChangePassword(ctx context.Context, id uint, oldPassword, newPassword string) error {
	if err := s.settings.ValidatePassword(ctx, newPassword); err != nil {
		return err
	}
	return s.uc.ChangePassword(ctx, id, oldPassword, newPassword)
}

func (s *UserService) SetUserAuthorities(ctx context.Context, id uint, authorityIDs []uint) error {
	return s.uc.SetUserAuthorities(ctx, id, authorityIDs)
}
func (s *UserService) SetUserSetting(ctx context.Context, id uint, setting map[string]any) error {
	return s.uc.SetUserSetting(ctx, id, setting)
}
