"""API key management service."""

import secrets

from sqlalchemy import select
from sqlalchemy.orm import Session

from fenliu.database import get_db
from fenliu.models import AppSetting


def generate_api_key() -> str:
    """Generate a secure random API key.

    Returns:
        A 64-character hexadecimal API key.

    """
    return secrets.token_hex(32)


def get_api_key(db: Session) -> str | None:
    """Retrieve the current API key from settings.

    Args:
        db: Database session.

    Returns:
        The API key if set, None otherwise.

    """
    setting = db.execute(select(AppSetting).where(AppSetting.key == "api_key")).scalar_one_or_none()
    if setting:
        return setting.value
    return None


def set_api_key(api_key: str) -> None:
    """Store or update the API key in settings.

    Args:
        api_key: The API key to store.

    """
    with get_db() as db:
        setting = db.execute(select(AppSetting).where(AppSetting.key == "api_key")).scalar_one_or_none()
        if setting:
            setting.value = api_key
        else:
            setting = AppSetting(key="api_key", value=api_key)
            db.add(setting)
        db.commit()


def delete_api_key() -> None:
    """Delete the current API key from settings."""
    with get_db() as db:
        setting = db.execute(select(AppSetting).where(AppSetting.key == "api_key")).scalar_one_or_none()
        if setting:
            db.delete(setting)
            db.commit()


def validate_api_key(key: str | None) -> bool:
    """Validate that the provided API key matches the stored key.

    Args:
        key: The API key to validate.

    Returns:
        True if the key is valid, False otherwise.

    """
    if not key:
        return False

    with get_db() as db:
        stored_key = get_api_key(db)
        return stored_key is not None and secrets.compare_digest(key, stored_key)
