package com.goldenchart.controller;

import com.goldenchart.dto.*;
import com.goldenchart.service.AdminService;
import com.goldenchart.service.RolePermissionService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin")
@RequiredArgsConstructor
public class AdminController {

    private final AdminService adminService;
    private final RolePermissionService rolePermissionService;

    private Long requireUserId(@RequestHeader(value = "X-User-Id", required = false) Long userId) {
        if (userId == null) {
            throw new org.springframework.web.server.ResponseStatusException(
                    org.springframework.http.HttpStatus.UNAUTHORIZED, "로그인이 필요합니다.");
        }
        rolePermissionService.requireAdmin(userId);
        return userId;
    }

    @PostMapping("/verify-password")
    public ResponseEntity<Map<String, Boolean>> verifyPassword(
            @RequestHeader("X-User-Id") Long userId,
            @RequestBody AdminVerifyRequest body) {
        adminService.verifyAdminPassword(userId, body != null ? body.getPassword() : null);
        return ResponseEntity.ok(Map.of("ok", true));
    }

    @GetMapping("/users")
    public List<UserDto> listUsers(@RequestHeader("X-User-Id") Long userId) {
        requireUserId(userId);
        return adminService.listUsers();
    }

    @PostMapping("/users")
    public UserDto createUser(
            @RequestHeader("X-User-Id") Long userId,
            @RequestBody CreateUserRequest body) {
        requireUserId(userId);
        return adminService.createUser(body);
    }

    @PutMapping("/users/{id}")
    public UserDto updateUser(
            @RequestHeader("X-User-Id") Long userId,
            @PathVariable Long id,
            @RequestBody UpdateUserRequest body) {
        requireUserId(userId);
        return adminService.updateUser(id, body, userId);
    }

    @DeleteMapping("/users/{id}")
    public ResponseEntity<Void> deleteUser(
            @RequestHeader("X-User-Id") Long userId,
            @PathVariable Long id) {
        requireUserId(userId);
        adminService.deleteUser(id, userId);
        return ResponseEntity.noContent().build();
    }

    @GetMapping("/role-permissions")
    public Map<String, Map<String, Boolean>> listRolePermissions(
            @RequestHeader("X-User-Id") Long userId) {
        requireUserId(userId);
        return rolePermissionService.listAllRolePermissions();
    }

    @PutMapping("/role-permissions")
    public ResponseEntity<Void> updateRolePermissions(
            @RequestHeader("X-User-Id") Long userId,
            @RequestBody RolePermissionsUpdateRequest body) {
        requireUserId(userId);
        rolePermissionService.updateRolePermissions(body);
        return ResponseEntity.ok().build();
    }
}
