package cn.reghao.tnb.auth.app.controller;

import cn.reghao.tnb.common.web.WebResult;
import cn.reghao.tnb.auth.app.model.vo.LoginRecordVo;
import cn.reghao.tnb.auth.app.security.form.AccountAuthToken;
import cn.reghao.tnb.auth.app.service.AccountTokenService;
import cn.reghao.tnb.auth.app.service.LoginAttemptService;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 账号登入日志接口
 *
 * @author reghao
 * @date 2023-07-31 10:34:41
 */
@Tag(name = "帐号登入日志接口")
@RestController
@RequestMapping("/api/account")
public class AccountRecordController {
	private final LoginAttemptService loginAttemptService;
	private final AccountTokenService accountTokenService;

	public AccountRecordController(LoginAttemptService loginAttemptService,
								   AccountTokenService accountTokenService) {
		this.loginAttemptService = loginAttemptService;
		this.accountTokenService = accountTokenService;
	}

	@Operation(summary = "获取登入日志列表", description = "N")
	@GetMapping("/record/list")
	public String list() {
		List<LoginRecordVo> list = loginAttemptService.getActiveLogin();
		return WebResult.success(list);
	}

	@Operation(summary = "注销某次登入", description = "N")
	@PostMapping(value = "/deactivate/{loginId}", produces = MediaType.APPLICATION_JSON_VALUE)
	public String deactivateLogin(@PathVariable("loginId") String loginId) {
		AccountAuthToken authToken = accountTokenService.getAuthToken();
		String currentLoginId = authToken.getLoginId();
		if (loginId.equals(currentLoginId)) {
			// 注销当前登入的设备
			accountTokenService.logout();
			return WebResult.success("/login");
		} else {
			accountTokenService.logout(loginId);
		}

		return WebResult.success();
	}
}
