package com.ruoyi.web.controller.front;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.generator.domain.front.dto.FrontLoginBody;
import com.ruoyi.generator.domain.front.dto.FrontRegisterBody;
import com.ruoyi.generator.service.front.IFrontUserService;
import com.ruoyi.web.service.front.FrontAuthService;

@RestController
@RequestMapping("/front/auth")
public class FrontAuthController extends BaseController
{
    @Autowired
    private FrontAuthService frontAuthService;

    @Autowired
    private IFrontUserService frontUserService;

    @Autowired
    private TokenService tokenService;

    @PostMapping("/register")
    public AjaxResult register(@RequestBody FrontRegisterBody body)
    {
        return toAjax(frontUserService.register(body));
    }

    @PostMapping("/login")
    public AjaxResult login(@RequestBody FrontLoginBody body)
    {
        AjaxResult ajax = AjaxResult.success();
        String username = body == null ? null : body.getUsername();
        String password = body == null ? null : body.getPassword();
        String token = frontAuthService.login(username, password);
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    @GetMapping("/profile")
    public AjaxResult profile()
    {
        return AjaxResult.success(frontAuthService.profile(SecurityUtils.getUserId()));
    }

    @PostMapping("/logout")
    public AjaxResult logout()
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        tokenService.delLoginUser(loginUser.getToken());
        return AjaxResult.success();
    }
}
