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

import db_pool


def _to_bool_with_default(value, default: bool = True) -> bool:
    if value is None:
        return default
    try:
        return bool(int(value))
    except Exception:
        try:
            return bool(value)
        except Exception:
            return default


def _normalize_notify_enabled(enabled) -> int:
    if isinstance(enabled, bool):
        return 1 if enabled else 0
    try:
        return 1 if int(enabled) else 0
    except Exception:
        return 1


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, 1 if verified else 0, 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 = ?
            """,
            (_normalize_notify_enabled(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 _to_bool_with_default(row[0], default=True)
        except Exception:
            return True
