package com.ruoyi.gateway.enhance.controller;

import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.gateway.enhance.auth.JwtTokenHelper;
import com.ruoyi.gateway.enhance.service.RouteUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;

/**
 * @author MrBird
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("route")
public class RouteLoginController {

    private final JwtTokenHelper tokenHelper;
    private final PasswordEncoder passwordEncoder;
    private final RouteUserService routeUserService;

    @GetMapping("login")
    public Mono<ResponseEntity<AjaxResult>> login(String username, String password) {
        String error = "认证失败，用户名或密码错误";
        return routeUserService.findByUsername(username)
                .map(u -> passwordEncoder.matches(password, u.getPassword()) ?
                        ResponseEntity.ok(AjaxResult.success("", tokenHelper.generateToken(u))) :
                        ResponseEntity.ok(AjaxResult.error(error)))
                .defaultIfEmpty(new ResponseEntity<>(AjaxResult.error(error), HttpStatus.OK));
    }
}
