from supabase import create_client
import time


class ADB:
    def __init__(self, url, key):
        self.url = url
        self.key = key
        self.db = create_client(url, key)
        self.oturum = None   # kullanıcı session

    # ================= AUTH =================

    def a_kayit_ol(self, email, sifre):
        try:
            return self.db.auth.sign_up({
                "email": email,
                "password": sifre
            })
        except Exception as e:
            print("Kayıt hatası:", e)
            return None

    def a_giris_yap(self, email, sifre):
        try:
            sonuc = self.db.auth.sign_in_with_password({
                "email": email,
                "password": sifre
            })

            self.oturum = sonuc.session   # session sakla
            return sonuc.user.id          # uid döndür

        except Exception as e:
            print("Giriş hatası:", e)
            return None

    # Oturum düşerse yenile
    def _kontrol_et(self):
        try:
            if self.oturum:
                self.db.auth.set_session(
                    self.oturum.access_token,
                    self.oturum.refresh_token
                )
        except:
            pass

    # ================= TABLO =================

    def add(self, tablo, uid, **veriler):
        """
        Örnek:
        add("users_data", uid, username="Ali Kaya", skor=34)
        """
        self._kontrol_et()

        try:
            veriler["user_id"] = uid
            return self.db.table(tablo).insert(veriler).execute()
        except Exception as e:
            print("Veri ekleme hatası:", e)
            return None

    def get(self, tablo, uid):
        self._kontrol_et()

        try:
            return self.db.table(tablo) \
                .select("*") \
                .eq("user_id", uid) \
                .single() \
                .execute().data
        except Exception as e:
            print("Veri alma hatası:", e)
            return None

    def update(self, tablo, uid, **veriler):
        self._kontrol_et()

        try:
            return self.db.table(tablo) \
                .update(veriler) \
                .eq("user_id", uid) \
                .execute()
        except Exception as e:
            print("Güncelleme hatası:", e)
            return None