"""Create admin user

Revision ID: 003_create_admin
Revises: 002_marathon_settings
Create Date: 2024-12-14

"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa
from passlib.context import CryptContext

# revision identifiers, used by Alembic.
revision: str = '003_create_admin'
down_revision: Union[str, None] = '002_marathon_settings'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")


def upgrade() -> None:
    # Hash the password
    password_hash = pwd_context.hash("RPQ586qq")

    # Insert admin user (ignore if already exists)
    op.execute(f"""
        INSERT INTO users (login, password_hash, nickname, role, created_at)
        VALUES ('admin', '{password_hash}', 'Admin', 'admin', NOW())
        ON CONFLICT (login) DO UPDATE SET
            password_hash = '{password_hash}',
            role = 'admin'
    """)


def downgrade() -> None:
    op.execute("DELETE FROM users WHERE login = 'admin'")
