package com.fluxup.app;

import android.content.Context;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.FirebaseFirestore;
import java.util.HashMap;
import java.util.Map;

public class UsuariosService {

    private static final FirebaseAuth mAuth = FirebaseAuth.getInstance();
    private static final FirebaseFirestore mFirestore = FirebaseFirestore.getInstance();

    public static void login(Context context, String email, String password, ServiceCallback<Usuario> callback) {
        mAuth.signInWithEmailAndPassword(email, password)
            .addOnCompleteListener(task -> {
                if (task.isSuccessful()) {
                    FirebaseUser user = mAuth.getCurrentUser();
                    if (user != null) {
                        // Buscar detalhes no Firestore
                        mFirestore.collection("users").document(user.getUid()).get()
                            .addOnSuccessListener(documentSnapshot -> {
                                Usuario usuario = documentSnapshot.toObject(Usuario.class);
                                if (usuario == null) {
                                    // Fallback if document not found
                                    usuario = new Usuario(user.getUid(), "", user.getEmail(), "", "");
                                }
                                callback.onSuccess(usuario);
                            })
                            .addOnFailureListener(e -> callback.onError(e.getMessage()));
                    }
                } else {
                    callback.onError(task.getException() != null ? task.getException().getMessage() : "Erro ao entrar");
                }
            });
    }

    public static void registar(Context context, Usuario usuario, ServiceCallback<Usuario> callback) {
        mAuth.createUserWithEmailAndPassword(usuario.email, usuario.palavra_passe)
            .addOnCompleteListener(task -> {
                if (task.isSuccessful()) {
                    FirebaseUser firebaseUser = mAuth.getCurrentUser();
                    if (firebaseUser != null) {
                        usuario.id_usuario = firebaseUser.getUid();
                        // Não salvar a senha no Firestore por segurança
                        usuario.palavra_passe = null;
                        
                        mFirestore.collection("users").document(firebaseUser.getUid()).set(usuario)
                            .addOnSuccessListener(aVoid -> callback.onSuccess(usuario))
                            .addOnFailureListener(e -> callback.onError(e.getMessage()));
                    }
                } else {
                    callback.onError(task.getException() != null ? task.getException().getMessage() : "Erro ao criar conta");
                }
            });
    }

    public static void recuperarPalavraPasse(Context context, String email, ServiceCallback<Void> callback) {
        mAuth.sendPasswordResetEmail(email)
            .addOnCompleteListener(task -> {
                if (task.isSuccessful()) {
                    callback.onSuccess(null);
                } else {
                    callback.onError(task.getException() != null ? task.getException().getMessage() : "Erro ao enviar email");
                }
            });
    }

    public interface ServiceCallback<T> {
        void onSuccess(T data);
        void onError(String error);
    }
}
