package com.izouma.immall.web;

import com.izouma.immall.repo.AuthorityRepo;
import com.izouma.immall.security.Authority;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import java.util.List;

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

    @PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/all")
    public List<Authority> all() {
        return authorityRepo.findAll();
    }

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

    @PostConstruct
    public void init() {
        authorityRepo.save(new Authority(Authority.NAMES.ROLE_ADMIN.name()));
        authorityRepo.save(new Authority(Authority.NAMES.ROLE_USER.name()));
        authorityRepo.save(new Authority(Authority.NAMES.ROLE_DEV.name()));
    }
}
