package com.devjob.controller;

import com.devjob.dto.ApiResponse;
import com.devjob.dto.MemberResponse;
import com.devjob.dto.RoleChangeRequest;
import com.devjob.domain.Role;
import com.devjob.service.JobService;
import com.devjob.service.MemberService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
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.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
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;

/**
 * EP25: 관리자 전용 API.
 * - SecurityConfig에서 "/api/admin/**"는 hasRole("ADMIN")으로 1차 차단되고,
 *   @EnableMethodSecurity + @PreAuthorize로 메서드 단위 2차 검증을 추가한다.
 */
@Tag(name = "관리자")
@RestController
@RequestMapping("/api/admin")
@RequiredArgsConstructor
public class AdminController {

    private final MemberService memberService;
    private final JobService jobService;

    @Operation(summary = "회원 목록 조회", security = @SecurityRequirement(name = "bearerAuth"))
    @PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/members")
    public ApiResponse<List<MemberResponse>> members(@RequestParam(required = false) Role role) {
        return ApiResponse.ok(memberService.findAll(role));
    }

    @Operation(summary = "회원 권한 변경", description = "회원의 역할을 USER/ADMIN으로 변경합니다.", security = @SecurityRequirement(name = "bearerAuth"))
    @PreAuthorize("hasRole('ADMIN')")
    @PatchMapping("/members/{id}/role")
    public ApiResponse<MemberResponse> changeRole(@PathVariable Long id, @RequestBody @Valid RoleChangeRequest request) {
        return ApiResponse.ok(memberService.changeRole(id, request.role()));
    }

    @Operation(summary = "공고 강제 삭제", description = "관리자 권한으로 채용 공고를 삭제합니다.", security = @SecurityRequirement(name = "bearerAuth"))
    @PreAuthorize("hasRole('ADMIN')")
    @DeleteMapping("/jobs/{id}")
    public ResponseEntity<Void> deleteJob(@PathVariable Long id) {
        jobService.delete(id);
        return ResponseEntity.noContent().build();
    }
}
