"""Flask CLI commands."""
from __future__ import annotations

import sys

import click
from flask import Flask, current_app

from backend.app.auth import hash_password
from backend.app.extensions import db
from backend.app.models import User, UserRole


def register_cli(app: Flask) -> None:
    @app.cli.command("create-admin")
    @click.argument("username")
    @click.argument("password")
    def create_admin(username: str, password: str) -> None:
        """Create an admin user. Used to bootstrap the first account."""
        min_len = current_app.config["MIN_PASSWORD_LENGTH"]
        if len(password) < min_len:
            click.echo(
                f"Error: password must be at least {min_len} characters.", err=True
            )
            sys.exit(2)

        if User.query.filter_by(username=username).first() is not None:
            click.echo(f"Error: username '{username}' already exists.", err=True)
            sys.exit(1)

        user = User(
            username=username,
            password_hash=hash_password(password),
            role=UserRole.ADMIN,
        )
        db.session.add(user)
        db.session.commit()
        click.echo(f"Admin user '{username}' created (id={user.id}).")
