# Generated by Django 4.2.5 on 2023-11-15 09:16

# Python imports
import uuid

from django.db import migrations


def update_pages(apps, schema_editor):
    try:
        Page = apps.get_model("db", "Page")
        PageBlock = apps.get_model("db", "PageBlock")
        PageLog = apps.get_model("db", "PageLog")

        updated_pages = []
        page_logs = []

        # looping through all the pages
        for page in Page.objects.all():
            page_blocks = PageBlock.objects.filter(
                page_id=page.id,
                project_id=page.project_id,
                workspace_id=page.workspace_id,
            ).order_by("sort_order")

            if page_blocks:
                # looping through all the page blocks in a page
                for page_block in page_blocks:
                    if page_block.issue is not None:
                        project_identifier = page.project.identifier
                        sequence_id = page_block.issue.sequence_id
                        transaction = uuid.uuid4().hex
                        embed_component = f'<issue-embed-component id="{transaction}" entity_name="issue" entity_identifier="{page_block.issue_id}" sequence_id="{sequence_id}" project_identifier="{project_identifier}" title="{page_block.name}"></issue-embed-component>'
                        page.description_html += embed_component

                        # create the page transaction for the issue
                        page_logs.append(
                            PageLog(
                                page_id=page_block.page_id,
                                transaction=transaction,
                                entity_identifier=page_block.issue_id,
                                entity_name="issue",
                                project_id=page.project_id,
                                workspace_id=page.workspace_id,
                                created_by_id=page_block.created_by_id,
                                updated_by_id=page_block.updated_by_id,
                            )
                        )
                    else:
                        # adding the page block name and description to the page description
                        page.description_html += f"<h2>{page_block.name}</h2>"
                        page.description_html += page_block.description_html

                updated_pages.append(page)

        Page.objects.bulk_update(
            updated_pages,
            ["description_html"],
            batch_size=100,
        )
        PageLog.objects.bulk_create(page_logs, batch_size=100)

    except Exception as e:
        print(e)


class Migration(migrations.Migration):
    dependencies = [
        ("db", "0048_auto_20231116_0713"),
    ]

    operations = [
        migrations.RunPython(update_pages),
    ]
