package com.zioinfo.esn.service;

import com.zioinfo.esn.auth.EsnUser;
import com.zioinfo.esn.mapper.UserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
@RequiredArgsConstructor
public class UserService {
    private final UserMapper mapper;
    private final PasswordEncoder passwordEncoder;

    public List<EsnUser> list(String tenantCode, String role) {
        return mapper.findAll(tenantCode, role);
    }

    public EsnUser get(Long id) { return mapper.findById(id); }

    public EsnUser create(EsnUser v, String rawPassword) {
        v.setPasswordHash(passwordEncoder.encode(rawPassword));
        mapper.insert(v);
        return mapper.findById(v.getId());
    }

    public EsnUser update(Long id, EsnUser v) {
        v.setId(id);
        mapper.update(v);
        return mapper.findById(id);
    }

    public void changePassword(Long id, String rawPassword) {
        mapper.updatePassword(id, passwordEncoder.encode(rawPassword));
    }

    public EsnUser setActive(Long id, boolean active) {
        EsnUser u = mapper.findById(id);
        if (u == null) return null;
        u.setActive(active);
        mapper.update(u);
        return mapper.findById(id);
    }

    public void delete(Long id) { mapper.delete(id); }
}
