#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import annotations

import db_pool


def get_user_by_email(email):
    """根据邮箱获取用户"""
    with db_pool.get_db() as conn:
        cursor = conn.cursor()
        cursor.execute("SELECT * FROM users WHERE email = ?", (email,))
        user = cursor.fetchone()
        return dict(user) if user else None


def update_user_email(user_id, email, verified=False):
    """更新用户邮箱"""
    with db_pool.get_db() as conn:
        cursor = conn.cursor()

        cursor.execute(
            """
            UPDATE users
            SET email = ?, email_verified = ?
            WHERE id = ?
            """,
            (email, int(verified), user_id),
        )
        conn.commit()
        return cursor.rowcount > 0


def update_user_email_notify(user_id, enabled):
    """更新用户邮件通知偏好"""
    with db_pool.get_db() as conn:
        cursor = conn.cursor()

        cursor.execute(
            """
            UPDATE users
            SET email_notify_enabled = ?
            WHERE id = ?
            """,
            (int(enabled), user_id),
        )
        conn.commit()
        return cursor.rowcount > 0


def get_user_email_notify(user_id):
    """获取用户邮件通知偏好（默认开启）"""
    with db_pool.get_db() as conn:
        cursor = conn.cursor()
        try:
            cursor.execute("SELECT email_notify_enabled FROM users WHERE id = ?", (user_id,))
            row = cursor.fetchone()
            if row is None:
                return True
            return bool(row[0]) if row[0] is not None else True
        except Exception:
            return True
