from sqlalchemy.orm import Session

from app.core.security import hash_password
from app.db.base import Base
from app.db.session import engine
from app.models import AdminUser, ProjectCourse, Role
from app.services.system_settings import ensure_default_settings


def create_tables() -> None:
    import app.models  # noqa: F401

    Base.metadata.create_all(bind=engine)


def seed_defaults(db: Session, admin_username: str, admin_password: str) -> None:
    roles = [
        ("system_admin", "系统管理员"),
        ("certificate_admin", "证书管理员"),
        ("readonly", "只读查看人员"),
    ]
    for code, name in roles:
        if not db.query(Role).filter(Role.code == code).first():
            db.add(Role(code=code, name=name))

    projects = [
        ("DBY", "大本营"),
        ("QSX", "七三线"),
    ]
    for code, name in projects:
        if not db.query(ProjectCourse).filter(ProjectCourse.code == code).first():
            db.add(
                ProjectCourse(
                    code=code,
                    name=name,
                    default_certificate_name="培训结业证书",
                    default_course_name=name,
                    default_stage_name=None,
                    default_template_code="classic",
                )
            )

    if not db.query(AdminUser).filter(AdminUser.username == admin_username).first():
        db.add(
            AdminUser(
                username=admin_username,
                password_hash=hash_password(admin_password),
                role_code="system_admin",
            )
        )
    ensure_default_settings(db)
    db.commit()
