# Generated by Django 5.2 on 2025-07-25 17:00
import django.db.models.functions.datetime
from django.conf import settings
from django.db import migrations, models
from constants.grant_types import GrantTypeChoices


class Migration(migrations.Migration):
    atomic = False

    update_sql = f"""
UPDATE api_taskcredit AS t
SET    credits      = 0,
       credits_used = 0,
       voided=TRUE
FROM (
    SELECT id,
           row_number() OVER (
               PARTITION BY user_id,
                            date_trunc('month', granted_date)
               ORDER BY granted_date
           ) AS rn
    FROM   api_taskcredit
    WHERE  plan        = 'free'
      AND  grant_type  = '{str(GrantTypeChoices.PLAN)}'                 -- use the literal value
      AND  granted_date >= '2025-06-01 00:00:00+00'
) AS d
WHERE t.id = d.id
  AND d.rn > 1;
"""

    dependencies = [
        ('api', '0063_taskcredit_grant_type'),
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        # dedupe
        migrations.RunSQL(
            sql=update_sql,
            reverse_sql=migrations.RunSQL.noop,
        ),
    ]
