"""admin_user 表 CRUD。"""
from __future__ import annotations

from datetime import datetime, timezone

from sqlalchemy import select
from sqlalchemy.orm import Session

from app.core.security import hash_password
from app.models.admin import AdminUser


def get_by_id(db: Session, admin_id: int) -> AdminUser | None:
    return db.get(AdminUser, admin_id)


def get_by_username(db: Session, username: str) -> AdminUser | None:
    stmt = select(AdminUser).where(AdminUser.username == username)
    return db.execute(stmt).scalar_one_or_none()


def create_admin(
    db: Session,
    *,
    username: str,
    password: str,
    role: str = "operator",
    plain_password: str | None = None,
    pages_override: list[str] | None = None,
) -> AdminUser:
    """建管理员。plain_password 非空则额外留存明文(后台 UI 建的账号传,供权限管理页复看);
    脚本/起后台建账号不传(留 None → 前端不显示密码)。
    pages_override:role=="custom" 时传专属可见页 key 列表;普通角色为 None。"""
    admin = AdminUser(
        username=username,
        password_hash=hash_password(password),
        role=role,
        plain_password=plain_password,
        pages_override=pages_override,
    )
    db.add(admin)
    db.commit()
    db.refresh(admin)
    return admin


def update_last_login(db: Session, admin: AdminUser) -> None:
    admin.last_login_at = datetime.now(timezone.utc)
    db.commit()


def list_admins(db: Session) -> list[AdminUser]:
    stmt = select(AdminUser).order_by(AdminUser.id)
    return list(db.execute(stmt).scalars().all())


def set_role(db: Session, admin: AdminUser, *, role: str) -> AdminUser:
    admin.role = role
    db.commit()
    db.refresh(admin)
    return admin


def set_status(db: Session, admin: AdminUser, *, status: str) -> AdminUser:
    admin.status = status
    db.commit()
    db.refresh(admin)
    return admin


def set_password(db: Session, admin: AdminUser, *, password: str) -> AdminUser:
    admin.password_hash = hash_password(password)
    db.commit()
    db.refresh(admin)
    return admin
