# Generated by Django 5.0.9 on 2024-10-18 07:35

from datetime import date, timedelta

import django.contrib.postgres.fields.ranges
from django.db import migrations
from psycopg.types.range import DateRange


def migrate_is_invested(apps, schema_editor):
    Portfolio = apps.get_model("wbportfolio", "Portfolio")
    from wbportfolio.models import Product

    for portfolio in Portfolio.objects.filter(is_invested=True):
        if portfolio.instruments.exists():
            min_inception_date = portfolio.instruments.earliest("inception_date").inception_date
        else:
            min_inception_date = date.min
        portfolio.invested_timespan = DateRange(min_inception_date if min_inception_date else date.min, date.max)
        portfolio.save()
    for product in Product.objects.filter(
        portfolios__in=Portfolio.objects.filter(is_invested=False).values("id")
    ).distinct():
        portfolio = product.portfolio
        if product.delisted_date:
            portfolio.invested_timespan = DateRange(product.inception_date, product.delisted_date)
        else:
            portfolio.invested_timespan = DateRange(
                product.inception_date if product.inception_date else date.min,
                product.primary_portfolio.assets.filter(underlying_instrument__instrument_type__key="product")
                .earliest("date")
                .date
                - timedelta(days=1),
            )
        portfolio.save()


class Migration(migrations.Migration):
    dependencies = [
        ("wbportfolio", "0068_trade_internal_trade_trade_marked_as_internal_and_more"),
    ]

    operations = [
        migrations.AddField(
            model_name="portfolio",
            name="invested_timespan",
            field=django.contrib.postgres.fields.ranges.DateRangeField(
                blank=True, help_text="Define when this portfolio is considered invested", null=True
            ),
        ),
        migrations.RunPython(migrate_is_invested),
        migrations.RemoveField(
            model_name="portfolio",
            name="is_invested",
        ),
    ]
