package com.zioinfo.signage.service;

import com.zioinfo.signage.auth.SignageUser;
import com.zioinfo.signage.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<SignageUser> list(String tenantCode, String role) {
        return mapper.findAll(tenantCode, role);
    }

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

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

    public SignageUser update(Long id, SignageUser 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 SignageUser setActive(Long id, boolean active) {
        SignageUser 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); }
}
