package com.izouma.nineth.web;

import com.izouma.nineth.enums.AuthorityName;
import com.izouma.nineth.repo.AuthorityRepo;
import com.izouma.nineth.security.Authority;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/authority")
@AllArgsConstructor
public class AuthorityController extends BaseController {
    private AuthorityRepo authorityRepo;

    @PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/all")
    public List<Authority> all() {
        List<Authority> list = authorityRepo.findAll();
        list = list.stream().filter(authority -> {
            //不显示普通用户和铸造者
            if(authority.getName().equals(AuthorityName.ROLE_USER.name())
                || authority.getName().equals(AuthorityName.ROLE_MINTER.name())){
                return false;
            }
            return !authority.isHide();
        }).collect(Collectors.toList());
        return list;
    }

    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/save")
    public Authority save(Authority authority) {
        return authorityRepo.save(authority);
    }
}
