# This file is part of django-ca (https://github.com/mathiasertl/django-ca).
#
# django-ca is free software: you can redistribute it and/or modify it under the terms of the GNU General
# Public License as published by the Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# django-ca is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the
# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License along with django-ca. If not, see
# <http://www.gnu.org/licenses/>.
#
# Generated by Django 5.0.1 on 2024-01-20 08:31

"""Data migration for various fields to extension fields.

This migrates the following fields:

* crl_url -> sign_crl_distribution_points
* issuer_alt_name -> sign_issuer_alternative_name
* issuer_url and ocsp_url -> sign_authority_information_access
"""


import typing

from django.db import migrations

from django_ca.migration_helpers import Migration0040Helper as Helper

if typing.TYPE_CHECKING:
    from django.db.backends.base.schema import BaseDatabaseSchemaEditor
    from django.db.migrations.state import StateApps


def populate_extension_fields(apps: "StateApps", schema_editor: "BaseDatabaseSchemaEditor") -> None:
    """Migrate to extension fields (forward migration)."""
    CertificateAuthority = apps.get_model("django_ca", "CertificateAuthority")
    for ca in CertificateAuthority.objects.all():
        Helper.crl_url_to_sign_crl_distribution_points(ca)
        Helper.issuer_alt_name_to_sign_issuer_alternative_name(ca)
        Helper.ocsp_url_and_issuer_url_to_sign_authority_information_access(ca)
        ca.save()


def reverse_extension_fields(apps: "StateApps", schema_editor: "BaseDatabaseSchemaEditor") -> None:
    """Migrate to old fields (backwards migration)."""
    CertificateAuthority = apps.get_model("django_ca", "CertificateAuthority")
    for ca in CertificateAuthority.objects.all():
        Helper.backwards_sign_crl_distribution_points_to_crl_url(ca)
        Helper.backwards_sign_issuer_alternative_name_to_issuer_url(ca)
        Helper.backwards_sign_authority_information_access_to_ocsp_url_and_issuer_url(ca)
        ca.save()


class Migration(migrations.Migration):  # noqa: D101
    dependencies = [  # noqa: RUF012
        ("django_ca", "0039_certificateauthority_sign_authority_information_access_and_more"),
    ]

    operations = [  # noqa: RUF012
        migrations.RunPython(populate_extension_fields, reverse_extension_fields),
    ]
