import json

from django.db import migrations, models


DEFAULT_PAYE_CONFIG = {
    "personal_relief": "2400",
    "insurance_relief_rate": "0.15",
    "insurance_relief_cap": "5000",
    "housing_levy_rate": "0.015",
    "include_housing_levy_in_paye": True,
    "paye_band1_limit": "24000",
    "paye_band1_rate": "0.10",
    "paye_band2_limit": "8333",
    "paye_band2_rate": "0.25",
    "paye_band3_limit": "467667",
    "paye_band3_rate": "0.30",
    "paye_band4_limit": "300000",
    "paye_band4_rate": "0.325",
    "paye_band5_threshold": "800000",
    "paye_band5_rate": "0.35",
}

DEFAULT_NSSF_CONFIG = {
    "rate": "0.06",
    "tier1_limit": "8000",
    "tier2_limit": "72000",
}


def seed_statutory_deduction_config(apps, schema_editor):
    Deduction = apps.get_model("human_resource", "Deduction")
    seeds = {
        "NSSF": ("nssf_tiered", DEFAULT_NSSF_CONFIG),
        "SHA": ("sha_percentage", {}),
        "SHIF": ("sha_percentage", {}),
        "PAYE": ("paye_progressive", DEFAULT_PAYE_CONFIG),
    }
    for title, (formula, cfg) in seeds.items():
        Deduction.objects.filter(deduction_title=title, recycle_bin=False).update(
            statutory_formula=formula,
            formula_config=json.dumps(cfg),
        )


class Migration(migrations.Migration):

    dependencies = [
        ("human_resource", "0009_remove_nhif_deprecate_sha"),
    ]

    operations = [
        migrations.AddField(
            model_name="deduction",
            name="formula_config",
            field=models.TextField(blank=True, default=""),
        ),
        migrations.AddField(
            model_name="deduction",
            name="statutory_formula",
            field=models.CharField(
                blank=True,
                choices=[
                    ("", "Standard"),
                    ("nssf_tiered", "NSSF tiered"),
                    ("sha_percentage", "SHA percentage"),
                    ("paye_progressive", "PAYE progressive"),
                    ("housing_levy", "Housing levy"),
                ],
                default="",
                max_length=30,
            ),
        ),
        migrations.RemoveField(
            model_name="hrpayrollsettings",
            name="minimum_basic_salary_warning",
        ),
        migrations.RunPython(seed_statutory_deduction_config, migrations.RunPython.noop),
    ]
