package com.tasteby.service;

import com.tasteby.domain.UserInfo;
import com.tasteby.mapper.UserMapper;
import com.tasteby.util.IdGenerator;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.server.ResponseStatusException;

import java.util.List;

@Service
public class UserService {

    private final UserMapper mapper;

    public UserService(UserMapper mapper) {
        this.mapper = mapper;
    }

    @Transactional
    public UserInfo findOrCreate(String provider, String providerId, String email, String nickname, String avatarUrl) {
        UserInfo existing = mapper.findByProviderAndProviderId(provider, providerId);
        if (existing != null) {
            mapper.updateLastLogin(existing.getId());
            return mapper.findById(existing.getId());
        }
        UserInfo user = UserInfo.builder()
                .id(IdGenerator.newId())
                .provider(provider)
                .providerId(providerId)
                .email(email)
                .nickname(nickname)
                .avatarUrl(avatarUrl)
                .build();
        mapper.insert(user);
        return mapper.findById(user.getId());
    }

    public UserInfo findById(String userId) {
        return mapper.findById(userId);
    }

    public List<UserInfo> findAllWithCounts(int limit, int offset) {
        return mapper.findAllWithCounts(limit, offset);
    }

    public int countAll() {
        return mapper.countAll();
    }

    @Transactional
    public void updateAdmin(String userId, boolean admin) {
        int rows = mapper.updateAdmin(userId, admin ? 1 : 0);
        if (rows == 0) {
            throw new ResponseStatusException(HttpStatus.NOT_FOUND, "User not found");
        }
    }
}
