package com.mosquito.project.permission;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 角色管理Controller - 角色CRUD API
 */
@RestController
@RequestMapping("/api/v1/roles")
public class RoleController {

    private final RoleService roleService;

    public RoleController(RoleService roleService) {
        this.roleService = roleService;
    }

    /**
     * 获取角色列表
     */
    @GetMapping
    public ResponseEntity<List<SysRole>> list() {
        return ResponseEntity.ok(roleService.findAll());
    }

    /**
     * 根据ID获取角色
     */
    @GetMapping("/{id}")
    public ResponseEntity<SysRole> getById(@PathVariable Long id) {
        return roleService.findById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    /**
     * 根据角色代码获取角色
     */
    @GetMapping("/code/{roleCode}")
    public ResponseEntity<SysRole> getByRoleCode(@PathVariable String roleCode) {
        return roleService.findByRoleCode(roleCode)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    /**
     * 创建角色
     */
    @PostMapping
    public ResponseEntity<SysRole> create(@RequestBody SysRole role) {
        try {
            SysRole saved = roleService.save(role);
            return ResponseEntity.ok(saved);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().build();
        }
    }

    /**
     * 更新角色
     */
    @PutMapping("/{id}")
    public ResponseEntity<SysRole> update(@PathVariable Long id, @RequestBody SysRole role) {
        return roleService.update(id, role)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    /**
     * 删除角色（软删除）
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> delete(@PathVariable Long id) {
        roleService.delete(id);
        return ResponseEntity.noContent().build();
    }

    /**
     * 检查角色代码是否存在
     */
    @GetMapping("/exists/{roleCode}")
    public ResponseEntity<Boolean> exists(@PathVariable String roleCode) {
        return ResponseEntity.ok(roleService.existsByRoleCode(roleCode));
    }
}
