# Generated by ChatGPT to convert Product.features into a related ProductFeature table

import json
from django.db import migrations, models


def copy_features_to_product_features(apps, schema_editor):
    Product = apps.get_model('shop', 'Product')
    ProductFeature = apps.get_model('shop', 'ProductFeature')
    db_table = Product._meta.db_table

    with schema_editor.connection.cursor() as cursor:
        cursor.execute(f"SELECT id, features FROM {db_table}")
        rows = cursor.fetchall()

    for product_id, features_value in rows:
        if not features_value:
            continue

        if isinstance(features_value, str):
            try:
                features = json.loads(features_value)
            except ValueError:
                continue
        else:
            features = features_value

        if not isinstance(features, dict):
            continue

        for name, value in features.items():
            if name and value is not None:
                ProductFeature.objects.create(
                    product_id=product_id,
                    name=str(name),
                    value=str(value)
                )


class Migration(migrations.Migration):

    dependencies = [
        ('shop', '0020_rename_shop_prod_view_log_prod_viewed_at_idx_shop_produc_product_b0e677_idx_and_more'),
    ]

    operations = [
        migrations.CreateModel(
            name='ProductFeature',
            fields=[
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(max_length=100)),
                ('value', models.CharField(max_length=255)),
                ('created_at', models.DateTimeField(auto_now_add=True)),
                ('product', models.ForeignKey(on_delete=models.deletion.CASCADE, related_name='features', to='shop.product')),
            ],
            options={
                'ordering': ['name'],
                'unique_together': {('product', 'name')},
            },
        ),
        migrations.RunPython(copy_features_to_product_features, reverse_code=migrations.RunPython.noop),
        migrations.RemoveField(
            model_name='product',
            name='features',
        ),
    ]
