package com.tasteby.service;

import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken;
import com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import com.tasteby.domain.UserInfo;
import com.tasteby.security.JwtTokenProvider;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;

import java.util.Collections;
import java.util.Map;

@Service
public class AuthService {

    private final UserService userService;
    private final JwtTokenProvider jwtProvider;
    private final GoogleIdTokenVerifier verifier;

    public AuthService(UserService userService, JwtTokenProvider jwtProvider,
                       @Value("${app.google.client-id}") String googleClientId) {
        this.userService = userService;
        this.jwtProvider = jwtProvider;
        this.verifier = new GoogleIdTokenVerifier.Builder(
                new NetHttpTransport(), GsonFactory.getDefaultInstance())
                .setAudience(Collections.singletonList(googleClientId))
                .build();
    }

    public Map<String, Object> loginGoogle(String idTokenString) {
        try {
            GoogleIdToken idToken = verifier.verify(idTokenString);
            if (idToken == null) {
                throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Invalid Google token");
            }
            GoogleIdToken.Payload payload = idToken.getPayload();

            UserInfo user = userService.findOrCreate(
                    "google",
                    payload.getSubject(),
                    payload.getEmail(),
                    (String) payload.get("name"),
                    (String) payload.get("picture"));

            // Convert to Map for JWT
            Map<String, Object> userMap = Map.of(
                    "id", user.getId(),
                    "email", user.getEmail() != null ? user.getEmail() : "",
                    "nickname", user.getNickname() != null ? user.getNickname() : "",
                    "is_admin", user.isAdmin()
            );
            String accessToken = jwtProvider.createToken(userMap);
            return Map.of("access_token", accessToken, "user", user);
        } catch (ResponseStatusException e) {
            throw e;
        } catch (Exception e) {
            throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Invalid Google token: " + e.getMessage());
        }
    }

    public UserInfo getCurrentUser(String userId) {
        UserInfo user = userService.findById(userId);
        if (user == null) {
            throw new ResponseStatusException(HttpStatus.NOT_FOUND, "User not found");
        }
        return user;
    }
}
