package com.nursinghome.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import com.nursinghome.common.ApiException;
import com.nursinghome.common.ApiResponse;
import com.nursinghome.dto.LoginRequest;
import com.nursinghome.dto.RegisterRequest;
import com.nursinghome.entity.User;
import com.nursinghome.service.FamilyService;
import com.nursinghome.service.UserService;
import com.nursinghome.util.PasswordUtil;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;

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

@RestController
@RequestMapping("/api/auth")
public class AuthController {
    private final UserService userService;
    private final FamilyService familyService;

    public AuthController(UserService userService, FamilyService familyService) {
        this.userService = userService;
        this.familyService = familyService;
    }

    @PostMapping("/login")
    public ApiResponse<Map<String, Object>> login(@Valid @RequestBody LoginRequest request) {
        User user = userService.findByUsername(request.getUsername());
        if (user == null) {
            throw new ApiException("账号不存在");
        }
        if (user.getStatus() != null && user.getStatus() == 0) {
            throw new ApiException("账号已被禁用");
        }
        if (!PasswordUtil.matches(request.getPassword(), user.getPassword())) {
            throw new ApiException("密码错误");
        }
        if (!PasswordUtil.isBcrypt(user.getPassword())) {
            userService.updatePassword(user.getId(), PasswordUtil.hash(request.getPassword()));
        }
        StpUtil.login(user.getId());

        user.setPassword(null);
        Map<String, Object> data = new HashMap<>();
        data.put("token", StpUtil.getTokenValue());
        data.put("role", user.getRole());
        data.put("user", user);
        return ApiResponse.success(data);
    }

    @PostMapping("/register")
    public ApiResponse<User> register(@Valid @RequestBody RegisterRequest request) {
        User user = familyService.registerFamily(
            request.getUsername(),
            request.getPassword(),
            request.getName(),
            request.getPhone(),
            request.getElderIdCard(),
            request.getRelationship()
        );
        return ApiResponse.success(user);
    }

    @PostMapping("/logout")
    public ApiResponse<Void> logout() {
        StpUtil.logout();
        return ApiResponse.success();
    }

    @GetMapping("/me")
    @SaCheckLogin
    public ApiResponse<User> me() {
        Long userId = Long.valueOf(StpUtil.getLoginId().toString());
        User user = userService.findById(userId);
        if (user != null) {
            user.setPassword(null);
        }
        return ApiResponse.success(user);
    }
}
