package com.izouma.dingdong.web;

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

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

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

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

    @PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/allAdmin")
    public List<Authority> allAdmin(){
        List<Authority> all = authorityRepo.findAll();
        all.remove(Authority.getInstance(Authority.NAMES.ROLE_USER));
        return all;
    }

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

    @PostConstruct
    public void init() {
        authorityRepo.save(Authority.getInstance(Authority.NAMES.ROLE_ADMIN));
        authorityRepo.save(Authority.getInstance(Authority.NAMES.ROLE_USER));
        authorityRepo.save(Authority.getInstance(Authority.NAMES.ROLE_DEV));
        authorityRepo.save(Authority.getInstance(Authority.NAMES.ROLE_CUSTOMER));
        authorityRepo.save(Authority.getInstance(Authority.NAMES.ROLE_FINANCE));
        authorityRepo.save(Authority.getInstance(Authority.NAMES.ROLE_INDUSTRY));
        authorityRepo.save(Authority.getInstance(Authority.NAMES.ROLE_LOCALIZATION));
    }
}
