package kr.co.accura.wbx.spring.auth;

import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * MFA/TOTP REST API
 * <p>
 * wbx.spring.mfa.enabled=true 일 때 활성화.
 * Google Authenticator / MS Authenticator 호환 TOTP.
 */
@RestController
@RequestMapping("${wbx.spring.api-prefix:/api}/auth/mfa")
@RequiredArgsConstructor
@ConditionalOnProperty(name = "wbx.spring.mfa.enabled", havingValue = "true")
public class MfaController {

    private final MfaService mfaService;

    /**
     * MFA 설정 시작 — QR 코드용 시크릿 + otpauth URI 반환
     */
    @PostMapping("/setup")
    public Map<String, String> setup(@AuthenticationPrincipal WbxUserDetails user) {
        return mfaService.setupMfa(user.getId());
    }

    /**
     * MFA 설정 완료 — TOTP 코드 검증 후 활성화 + 백업 코드 발급
     */
    @PostMapping("/setup/verify")
    public Map<String, Object> verifySetup(@AuthenticationPrincipal WbxUserDetails user,
                                            @Valid @RequestBody CodeRequest req) {
        return mfaService.verifySetup(user.getId(), req.code());
    }

    /**
     * MFA 비활성화 (본인 또는 SA)
     */
    @DeleteMapping
    public Map<String, String> disable(@AuthenticationPrincipal WbxUserDetails user) {
        mfaService.disableMfa(user.getId());
        return Map.of("detail", "MFA disabled");
    }

    /**
     * 백업 코드로 인증 (로그인 2단계 대안)
     */
    @PostMapping("/backup-verify")
    public Map<String, Object> backupVerify(@RequestBody Map<String, Object> req) {
        Long userId = ((Number) req.get("user_id")).longValue();
        String code = (String) req.get("backup_code");
        boolean valid = mfaService.verifyBackupCode(userId, code);
        return Map.of("valid", valid);
    }

    public record CodeRequest(@NotBlank String code) {}
}
