"""Schaeffler standard materials — add schaeffler_code column and seed 35 materials

Revision ID: 019
Revises: 018
Create Date: 2026-03-02
"""
from alembic import op
import sqlalchemy as sa
import uuid
from datetime import datetime

revision = "019"
down_revision = "018"
branch_labels = None
depends_on = None


def upgrade() -> None:
    op.add_column("materials", sa.Column("schaeffler_code", sa.Integer(), nullable=True))

    from app.data.schaeffler_materials import SCHAEFFLER_MATERIALS

    conn = op.get_bind()
    now = datetime.utcnow().isoformat()
    for mat in SCHAEFFLER_MATERIALS:
        desc = mat["description"].replace("'", "''")
        name = mat["name"].replace("'", "''")
        conn.execute(sa.text(
            f"INSERT INTO materials (id, name, description, source, schaeffler_code, created_at, updated_at) "
            f"VALUES ('{uuid.uuid4()}', '{name}', '{desc}', '{mat['source']}', "
            f"{mat['schaeffler_code']}, '{now}', '{now}') "
            f"ON CONFLICT (name) DO NOTHING"
        ))


def downgrade() -> None:
    op.execute("DELETE FROM materials WHERE source = 'schaeffler_standard'")
    op.drop_column("materials", "schaeffler_code")
