package com.hertz.modules.system.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.hertz.common.api.ApiResponse;
import com.hertz.modules.system.entity.SysRole;
import com.hertz.modules.system.service.RoleService;
import java.util.List;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/system/roles")
public class RoleController {
  private final RoleService roleService;

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

  @GetMapping
  @PreAuthorize("hasRole('ADMIN') or hasAuthority('system:role:view')")
  public ApiResponse<List<SysRole>> list() {
    return ApiResponse.ok(roleService.listEnabledRoles());
  }

  @GetMapping("/page")
  @PreAuthorize("hasRole('ADMIN') or hasAuthority('system:role:view')")
  public ApiResponse<IPage<SysRole>> page(
      @RequestParam(defaultValue = "1") int page,
      @RequestParam(defaultValue = "10") int size,
      @RequestParam(required = false) String keyword
  ) {
    return ApiResponse.ok(roleService.pageRoles(page, size, keyword));
  }

  @PostMapping
  @PreAuthorize("hasRole('ADMIN') or hasAuthority('system:role:add')")
  public ApiResponse<Void> create(@RequestBody SysRole role) {
    roleService.saveRole(role);
    return ApiResponse.ok();
  }

  @PutMapping
  @PreAuthorize("hasRole('ADMIN') or hasAuthority('system:role:edit')")
  public ApiResponse<Void> update(@RequestBody SysRole role) {
    roleService.updateRole(role);
    return ApiResponse.ok();
  }

  @DeleteMapping("/{id}")
  @PreAuthorize("hasRole('ADMIN') or hasAuthority('system:role:remove')")
  public ApiResponse<Void> delete(@PathVariable("id") Long id) {
    roleService.deleteRole(id);
    return ApiResponse.ok();
  }

  @GetMapping("/{id}/menus")
  @PreAuthorize("hasRole('ADMIN') or hasAuthority('system:role:view')")
  public ApiResponse<List<Long>> getRoleMenus(@PathVariable("id") Long id) {
    return ApiResponse.ok(roleService.getRoleMenuIds(id));
  }

  public record UpdateRoleMenusRequest(List<Long> menuIds) {
  }

  @PutMapping("/{id}/menus")
  @PreAuthorize("hasRole('ADMIN') or hasAuthority('system:role:assign')")
  public ApiResponse<Void> updateRoleMenus(@PathVariable("id") Long id, @RequestBody UpdateRoleMenusRequest req) {
    roleService.updateRolePermissions(id, req.menuIds());
    return ApiResponse.ok();
  }
}

