package com.ga.api.controller.system;

import com.ga.api.service.system.UserService;
import com.ga.common.annotation.DataChangeLog;
import com.ga.common.annotation.RequirePermission;
import com.ga.common.model.ApiResponse;
import com.ga.common.model.PageResponse;
import com.ga.core.vo.user.UserResp;
import com.ga.core.vo.user.UserSaveReq;
import com.ga.core.vo.user.UserSearchParam;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

@Tag(name = "사용자 관리")
@RestController
@RequestMapping("/api/system/users")
@RequiredArgsConstructor
public class UserController {

    private final UserService service;

    @GetMapping
    @RequirePermission(menu = "SYSTEM_USER", perm = "READ")
    public ApiResponse<PageResponse<UserResp>> list(@ModelAttribute UserSearchParam param) {
        return ApiResponse.ok(service.list(param));
    }

    @GetMapping("/{userId}")
    @RequirePermission(menu = "SYSTEM_USER", perm = "READ")
    public ApiResponse<UserResp> detail(@PathVariable Long userId) {
        return ApiResponse.ok(service.detail(userId));
    }

    @PostMapping
    @RequirePermission(menu = "SYSTEM_USER", perm = "CREATE")
    @DataChangeLog(menu = "SYSTEM_USER", table = "users")
    public ApiResponse<Long> create(@Valid @RequestBody UserSaveReq req) {
        return ApiResponse.ok(service.create(req));
    }

    @PutMapping("/{userId}")
    @RequirePermission(menu = "SYSTEM_USER", perm = "UPDATE")
    @DataChangeLog(menu = "SYSTEM_USER", table = "users")
    public ApiResponse<Void> update(@PathVariable Long userId, @Valid @RequestBody UserSaveReq req) {
        service.update(userId, req);
        return ApiResponse.ok();
    }

    @PutMapping("/{userId}/reset-password")
    @RequirePermission(menu = "SYSTEM_USER", perm = "UPDATE")
    public ApiResponse<Void> resetPassword(@PathVariable Long userId) {
        service.resetPassword(userId);
        return ApiResponse.ok();
    }

    @PutMapping("/{userId}/unlock")
    @RequirePermission(menu = "SYSTEM_USER", perm = "UPDATE")
    public ApiResponse<Void> unlock(@PathVariable Long userId) {
        service.unlock(userId);
        return ApiResponse.ok();
    }

    /**
     * 전화번호 단독 패치. SMS 알림 발신을 위한 phone 등록·정정 경로.
     * loginId/userName 같은 NotBlank 필드를 강제하지 않는다.
     */
    @PutMapping("/{userId}/phone")
    @RequirePermission(menu = "SYSTEM_USER", perm = "UPDATE")
    @DataChangeLog(menu = "SYSTEM_USER", table = "users")
    public ApiResponse<Void> updatePhone(@PathVariable Long userId, @RequestBody PhoneReq req) {
        service.updatePhone(userId, req.getPhone());
        return ApiResponse.ok();
    }

    @lombok.Data
    public static class PhoneReq {
        private String phone;
    }
}
