"""Migrate existing product data to translation tables

Revision ID: b4c5d6e7f8a9
Revises: a3b4c5d6e7f8
Create Date: 2025-12-11

This migration:
1. Copies existing title/description from marketplace_products to
   marketplace_product_translations (default language: 'en')
2. Parses existing price strings to numeric values
3. Removes the old title/description columns from marketplace_products

Since we're not live yet, we can safely remove the old columns
after migrating the data to the new structure.
"""

import re
from collections.abc import Sequence

import sqlalchemy as sa
from sqlalchemy import text

from alembic import op

# revision identifiers, used by Alembic.
revision: str = "b4c5d6e7f8a9"
down_revision: str | None = "a3b4c5d6e7f8"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None


def parse_price(price_str: str) -> float | None:
    """Parse price string like '19.99 EUR' to float."""
    if not price_str:
        return None

    # Extract numeric value
    numbers = re.findall(r"[\d.,]+", str(price_str))
    if numbers:
        num_str = numbers[0].replace(",", ".")
        try:
            return float(num_str)
        except ValueError:
            pass
    return None


def upgrade() -> None:
    conn = op.get_bind()

    # Step 1: Migrate existing title/description to translations table
    # Default language is 'en' for existing data
    conn.execute(
        text("""
            INSERT INTO marketplace_product_translations
                (marketplace_product_id, language, title, description, created_at, updated_at)
            SELECT
                id,
                'en',
                title,
                description,
                created_at,
                updated_at
            FROM marketplace_products
            WHERE title IS NOT NULL
        """)
    )

    # Step 2: Parse prices to numeric values
    # Get all marketplace products with prices
    result = conn.execute(
        text("SELECT id, price, sale_price FROM marketplace_products")
    )

    for row in result:
        price_numeric = parse_price(row.price) if row.price else None
        sale_price_numeric = parse_price(row.sale_price) if row.sale_price else None

        if price_numeric is not None or sale_price_numeric is not None:
            conn.execute(
                text("""
                    UPDATE marketplace_products
                    SET price_numeric = :price_numeric,
                        sale_price_numeric = :sale_price_numeric
                    WHERE id = :id
                """),
                {
                    "id": row.id,
                    "price_numeric": price_numeric,
                    "sale_price_numeric": sale_price_numeric,
                },
            )

    # Step 3: Since we're not live, remove the old title/description columns
    # from marketplace_products (data is now in translations table)
    op.drop_column("marketplace_products", "title")
    op.drop_column("marketplace_products", "description")


def downgrade() -> None:
    # Re-add title and description columns
    op.add_column(
        "marketplace_products",
        sa.Column("title", sa.String(), nullable=True),
    )
    op.add_column(
        "marketplace_products",
        sa.Column("description", sa.String(), nullable=True),
    )

    # Copy data back from translations (only 'en' translations)
    conn = op.get_bind()
    conn.execute(
        text("""
            UPDATE marketplace_products
            SET title = (
                SELECT title FROM marketplace_product_translations
                WHERE marketplace_product_translations.marketplace_product_id = marketplace_products.id
                AND marketplace_product_translations.language = 'en'
            ),
            description = (
                SELECT description FROM marketplace_product_translations
                WHERE marketplace_product_translations.marketplace_product_id = marketplace_products.id
                AND marketplace_product_translations.language = 'en'
            )
        """)
    )

    # Delete the migrated translations
    conn.execute(
        text("DELETE FROM marketplace_product_translations WHERE language = 'en'")
    )
