package kr.co.accura.wtm.api;

import kr.co.accura.wbx.spring.auth.WbxUserDetails;
import kr.co.accura.wtm.domain.user.repository.UserRoleRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

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

/**
 * WTM-specific auth endpoints that supplement wbx-spring-core's AuthController.
 * Overrides /me to include WTM role information from user_roles table.
 */
@RestController
@RequiredArgsConstructor
public class WtmAuthController {

    private final UserRoleRepository userRoleRepository;

    /**
     * 내 정보 조회 — WTM 역할 포함 (별도 경로)
     */
    @GetMapping("/api/wtm/auth/me/profile")
    public Map<String, Object> me(@AuthenticationPrincipal WbxUserDetails user) {
        // wtm user_roles에서 역할 코드 조회 (email 매칭)
        List<String> roles = userRoleRepository.findRoleCodesByUserEmail(user.getEmail());
        if (roles.isEmpty() && user.isAdmin()) {
            roles = List.of("SA");
        }

        Map<String, Object> result = new HashMap<>();
        result.put("id", user.getId());
        result.put("email", user.getEmail());
        result.put("username", user.getUsername());
        result.put("full_name", user.getFullName());
        result.put("is_admin", user.isAdmin());
        result.put("department_id", user.getDepartmentId() != null ? user.getDepartmentId() : 0);
        result.put("roles", roles);
        return result;
    }

    /**
     * SSO initiation — redirects to OAuth2 authorization endpoint.
     * Requires Azure Entra ID configuration.
     */
    @GetMapping("/api/wtm/auth/sso")
    public ResponseEntity<Map<String, String>> ssoInitiate() {
        // TODO: Redirect to OAuth2 authorization URI once Azure Entra ID is configured
        return ResponseEntity.status(501)
                .body(Map.of("message", "SSO not yet configured. Azure Entra ID integration pending."));
    }

    /**
     * SSO callback — handled by Spring Security OAuth2 filter chain.
     * This endpoint exists for documentation; actual handling is done by SsoSuccessHandler.
     */
    @GetMapping("/api/wtm/auth/sso/callback")
    public ResponseEntity<Map<String, String>> ssoCallback() {
        return ResponseEntity.status(501)
                .body(Map.of("message", "SSO callback handled by Spring Security OAuth2."));
    }

    /**
     * Password reset request — sends reset link to email.
     */
    @PostMapping("/api/wtm/auth/password/reset")
    public ResponseEntity<Map<String, String>> resetPassword(@RequestBody Map<String, String> request) {
        // TODO: Implement password reset email flow
        String email = request.get("email");
        return ResponseEntity.ok(Map.of(
                "message", "비밀번호 재설정 링크가 이메일로 전송되었습니다.",
                "email", email != null ? email : ""
        ));
    }
}
