import decimal
import uuid
from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):
    dependencies = [
        ("club_finance", "0005_general_ledger_accrual_three_statement"),
        ("federations", "0009_tournament_extra_time_resolution"),
        ("club_commercial", "0001_initial"),
        ("users", "0002_account_security"),
    ]

    operations = [
        migrations.CreateModel(
            name="FFPRegulatoryPolicy",
            fields=[
                ("id", models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
                ("name", models.CharField(max_length=140)),
                ("version", models.PositiveIntegerField(default=1)),
                ("effective_from", models.DateTimeField()),
                ("effective_to", models.DateTimeField(blank=True, null=True)),
                ("rolling_seasons", models.PositiveSmallIntegerField(default=3)),
                ("max_aggregate_loss", models.DecimalField(decimal_places=8, default=decimal.Decimal("0"), max_digits=24)),
                ("owner_contribution_cap", models.DecimalField(decimal_places=8, default=decimal.Decimal("0"), max_digits=24)),
                ("max_squad_cost_ratio", models.DecimalField(decimal_places=4, default=decimal.Decimal("0.70"), max_digits=8)),
                ("max_wage_to_revenue_ratio", models.DecimalField(decimal_places=4, default=decimal.Decimal("0.70"), max_digits=8)),
                ("warning_buffer_pct", models.DecimalField(decimal_places=2, default=decimal.Decimal("10"), max_digits=5)),
                ("require_full_window", models.BooleanField(default=False)),
                ("require_related_party_fair_value", models.BooleanField(default=True)),
                ("permitted_exclusion_types", models.JSONField(blank=True, default=list)),
                ("rules", models.JSONField(blank=True, default=dict)),
                ("is_active", models.BooleanField(default=True)),
                ("created_at", models.DateTimeField(auto_now_add=True)),
                ("federation", models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name="ffp_regulatory_policies", to="federations.federation")),
            ],
            options={"ordering": ["federation_id", "-effective_from", "-version"], "indexes": [models.Index(fields=["federation", "is_active", "effective_from"], name="cf_reg_policy_active_idx")]},
        ),
        migrations.AddConstraint(model_name="ffpregulatorypolicy", constraint=models.UniqueConstraint(fields=("federation", "name", "version"), name="cf_reg_policy_version_uq")),
        migrations.AddConstraint(model_name="ffpregulatorypolicy", constraint=models.CheckConstraint(condition=models.Q(("rolling_seasons__gte", 1)), name="cf_reg_policy_window_pos")),
        migrations.AddConstraint(model_name="ffpregulatorypolicy", constraint=models.CheckConstraint(condition=models.Q(("max_aggregate_loss__gte", 0)), name="cf_reg_policy_loss_nonneg")),
        migrations.AddConstraint(model_name="ffpregulatorypolicy", constraint=models.CheckConstraint(condition=models.Q(("owner_contribution_cap__gte", 0)), name="cf_reg_policy_owner_cap_nonneg")),
        migrations.AddConstraint(model_name="ffpregulatorypolicy", constraint=models.CheckConstraint(condition=models.Q(("max_squad_cost_ratio__gte", 0)), name="cf_reg_policy_squad_ratio_nonneg")),
        migrations.AddConstraint(model_name="ffpregulatorypolicy", constraint=models.CheckConstraint(condition=models.Q(("max_wage_to_revenue_ratio__gte", 0)), name="cf_reg_policy_wage_ratio_nonneg")),
        migrations.AddConstraint(model_name="ffpregulatorypolicy", constraint=models.CheckConstraint(condition=models.Q(("warning_buffer_pct__gte", 0), ("warning_buffer_pct__lte", 100)), name="cf_reg_policy_warning_pct")),
        migrations.AddConstraint(model_name="ffpregulatorypolicy", constraint=models.CheckConstraint(condition=(models.Q(effective_to__isnull=True) | models.Q(effective_to__gt=models.F("effective_from"))), name="cf_reg_policy_dates_order")),

        migrations.CreateModel(
            name="FFPRegulatoryAdjustment",
            fields=[
                ("id", models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
                ("adjustment_type", models.CharField(choices=[("YOUTH_DEVELOPMENT", "Youth development exclusion"), ("INFRASTRUCTURE", "Infrastructure exclusion"), ("COMMUNITY", "Community/social exclusion"), ("WOMENS_FOOTBALL", "Women's football exclusion"), ("OTHER_PERMITTED", "Other permitted exclusion")], max_length=32)),
                ("amount", models.DecimalField(decimal_places=8, max_digits=24)),
                ("status", models.CharField(choices=[("DRAFT", "Draft"), ("SUBMITTED", "Submitted"), ("APPROVED", "Approved"), ("REJECTED", "Rejected")], default="DRAFT", max_length=16)),
                ("source_type", models.CharField(blank=True, default="", max_length=80)),
                ("source_id", models.CharField(blank=True, default="", max_length=120)),
                ("explanation", models.TextField(blank=True, default="")),
                ("evidence", models.JSONField(blank=True, default=dict)),
                ("submitted_at", models.DateTimeField(blank=True, null=True)),
                ("reviewed_at", models.DateTimeField(blank=True, null=True)),
                ("created_at", models.DateTimeField(auto_now_add=True)),
                ("club", models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name="ffp_regulatory_adjustments", to="clubs.club")),
                ("period", models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name="ffp_regulatory_adjustments", to="club_finance.accountingperiod")),
                ("requested_by", models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name="requested_ffp_adjustments", to="users.user")),
                ("reviewed_by", models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name="reviewed_ffp_adjustments", to="users.user")),
            ],
            options={"ordering": ["-created_at", "id"], "indexes": [models.Index(fields=["club", "period", "status"], name="cf_reg_adjust_status_idx")]},
        ),
        migrations.AddConstraint(model_name="ffpregulatoryadjustment", constraint=models.CheckConstraint(condition=models.Q(("amount__gt", 0)), name="cf_reg_adjust_amount_pos")),
        migrations.AddConstraint(model_name="ffpregulatoryadjustment", constraint=models.UniqueConstraint(condition=~models.Q(source_id=""), fields=("club", "period", "adjustment_type", "source_type", "source_id"), name="cf_reg_adjust_source_uq")),

        migrations.CreateModel(
            name="FFPRelatedPartyReview",
            fields=[
                ("id", models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
                ("status", models.CharField(choices=[("DISCLOSED", "Disclosed"), ("UNDER_REVIEW", "Under review"), ("APPROVED", "Approved"), ("REJECTED", "Rejected")], default="DISCLOSED", max_length=16)),
                ("relationship_summary", models.TextField(blank=True, default="")),
                ("reported_revenue", models.DecimalField(decimal_places=8, default=decimal.Decimal("0"), max_digits=24)),
                ("fair_value", models.DecimalField(blank=True, decimal_places=8, max_digits=24, null=True)),
                ("allowed_revenue", models.DecimalField(blank=True, decimal_places=8, max_digits=24, null=True)),
                ("evidence", models.JSONField(blank=True, default=dict)),
                ("reviewed_at", models.DateTimeField(blank=True, null=True)),
                ("created_at", models.DateTimeField(auto_now_add=True)),
                ("agreement", models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name="ffp_related_party_reviews", to="club_commercial.sponsorshipagreement")),
                ("club", models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name="ffp_related_party_reviews", to="clubs.club")),
                ("disclosed_by", models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name="disclosed_related_party_reviews", to="users.user")),
                ("period", models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name="ffp_related_party_reviews", to="club_finance.accountingperiod")),
                ("reviewed_by", models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name="reviewed_related_party_reviews", to="users.user")),
            ],
            options={"ordering": ["-created_at", "id"], "indexes": [models.Index(fields=["club", "period", "status"], name="cf_reg_related_status_idx")]},
        ),
        migrations.AddConstraint(model_name="ffprelatedpartyreview", constraint=models.UniqueConstraint(fields=("agreement", "period"), name="cf_reg_related_review_uq")),
        migrations.AddConstraint(model_name="ffprelatedpartyreview", constraint=models.CheckConstraint(condition=models.Q(("reported_revenue__gte", 0)), name="cf_reg_related_report_nonneg")),
        migrations.AddConstraint(model_name="ffprelatedpartyreview", constraint=models.CheckConstraint(condition=(models.Q(fair_value__isnull=True) | models.Q(fair_value__gte=0)), name="cf_reg_related_fair_nonneg")),
        migrations.AddConstraint(model_name="ffprelatedpartyreview", constraint=models.CheckConstraint(condition=(models.Q(allowed_revenue__isnull=True) | models.Q(allowed_revenue__gte=0)), name="cf_reg_related_allowed_nonneg")),

        migrations.CreateModel(
            name="FFPRegulatoryAssessment",
            fields=[
                ("id", models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
                ("status", models.CharField(choices=[("COMPLIANT", "Compliant"), ("WARNING", "Warning"), ("REVIEW_REQUIRED", "Review required"), ("BREACH", "Breach")], max_length=20)),
                ("relevant_revenue", models.DecimalField(decimal_places=8, max_digits=24)),
                ("base_expense", models.DecimalField(decimal_places=8, max_digits=24)),
                ("approved_exclusions", models.DecimalField(decimal_places=8, default=decimal.Decimal("0"), max_digits=24)),
                ("related_party_revenue_reduction", models.DecimalField(decimal_places=8, default=decimal.Decimal("0"), max_digits=24)),
                ("owner_contribution_allowance", models.DecimalField(decimal_places=8, default=decimal.Decimal("0"), max_digits=24)),
                ("regulatory_expense", models.DecimalField(decimal_places=8, max_digits=24)),
                ("current_result", models.DecimalField(decimal_places=8, max_digits=24)),
                ("rolling_result", models.DecimalField(decimal_places=8, max_digits=24)),
                ("acceptable_loss_limit", models.DecimalField(decimal_places=8, max_digits=24)),
                ("squad_cost", models.DecimalField(decimal_places=8, max_digits=24)),
                ("wage_cost", models.DecimalField(decimal_places=8, max_digits=24)),
                ("squad_cost_ratio", models.DecimalField(blank=True, decimal_places=6, max_digits=12, null=True)),
                ("wage_to_revenue_ratio", models.DecimalField(blank=True, decimal_places=6, max_digits=12, null=True)),
                ("reasons", models.JSONField(blank=True, default=list)),
                ("window_evidence", models.JSONField(blank=True, default=dict)),
                ("checksum", models.CharField(max_length=64)),
                ("assessed_at", models.DateTimeField(auto_now_add=True)),
                ("club", models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name="ffp_regulatory_assessments", to="clubs.club")),
                ("federation", models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name="ffp_regulatory_assessments", to="federations.federation")),
                ("policy", models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name="assessments", to="club_finance.ffpregulatorypolicy")),
                ("target_period", models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name="ffp_regulatory_assessments", to="club_finance.accountingperiod")),
            ],
            options={"ordering": ["-assessed_at", "id"], "indexes": [models.Index(fields=["club", "target_period", "status"], name="cf_reg_assess_club_idx"), models.Index(fields=["federation", "status", "assessed_at"], name="cf_reg_assess_fed_idx")]},
        ),
        migrations.AddConstraint(model_name="ffpregulatoryassessment", constraint=models.CheckConstraint(condition=~models.Q(("checksum", "")), name="cf_reg_assess_checksum_nonempty")),

        migrations.CreateModel(
            name="FFPRegulatorySubmission",
            fields=[
                ("id", models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
                ("status", models.CharField(choices=[("DRAFT", "Draft"), ("SUBMITTED", "Submitted"), ("UNDER_REVIEW", "Under review"), ("INFO_REQUESTED", "Information requested"), ("ACCEPTED", "Accepted"), ("BREACH", "Breach confirmed"), ("WITHDRAWN", "Withdrawn")], default="DRAFT", max_length=20)),
                ("attestation_text", models.TextField(blank=True, default="")),
                ("attested_at", models.DateTimeField(blank=True, null=True)),
                ("submitted_at", models.DateTimeField(blank=True, null=True)),
                ("payload_checksum", models.CharField(max_length=64)),
                ("created_at", models.DateTimeField(auto_now_add=True)),
                ("updated_at", models.DateTimeField(auto_now=True)),
                ("assessment", models.OneToOneField(on_delete=django.db.models.deletion.PROTECT, related_name="submission", to="club_finance.ffpregulatoryassessment")),
                ("attested_by", models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name="ffp_attestations", to="users.user")),
                ("club", models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name="ffp_regulatory_submissions", to="clubs.club")),
                ("federation", models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name="ffp_regulatory_submissions", to="federations.federation")),
            ],
            options={"ordering": ["-created_at", "id"], "indexes": [models.Index(fields=["federation", "status", "created_at"], name="cf_reg_submit_queue_idx")]},
        ),
        migrations.AddConstraint(model_name="ffpregulatorysubmission", constraint=models.CheckConstraint(condition=~models.Q(("payload_checksum", "")), name="cf_reg_submit_checksum_nonempty")),

        migrations.CreateModel(
            name="FFPFederationReviewCase",
            fields=[
                ("id", models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
                ("status", models.CharField(choices=[("OPEN", "Open"), ("UNDER_REVIEW", "Under review"), ("INFO_REQUESTED", "Information requested"), ("CLEARED", "Cleared"), ("BREACH_CONFIRMED", "Breach confirmed"), ("SANCTIONED", "Sanctioned"), ("APPEALED", "Appealed"), ("CLOSED", "Closed")], default="OPEN", max_length=24)),
                ("findings", models.JSONField(blank=True, default=dict)),
                ("sanctions", models.JSONField(blank=True, default=list)),
                ("opened_at", models.DateTimeField(auto_now_add=True)),
                ("decided_at", models.DateTimeField(blank=True, null=True)),
                ("closed_at", models.DateTimeField(blank=True, null=True)),
                ("updated_at", models.DateTimeField(auto_now=True)),
                ("assigned_to", models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name="assigned_ffp_cases", to="users.user")),
                ("federation", models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name="ffp_review_cases", to="federations.federation")),
                ("submission", models.OneToOneField(on_delete=django.db.models.deletion.PROTECT, related_name="review_case", to="club_finance.ffpregulatorysubmission")),
            ],
            options={"ordering": ["-opened_at", "id"], "indexes": [models.Index(fields=["federation", "status", "opened_at"], name="cf_reg_case_queue_idx")]},
        ),

        migrations.CreateModel(
            name="FFPRegulatoryCaseEvent",
            fields=[
                ("id", models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
                ("event_type", models.CharField(max_length=48)),
                ("payload", models.JSONField(blank=True, default=dict)),
                ("created_at", models.DateTimeField(auto_now_add=True)),
                ("actor", models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name="ffp_case_events", to="users.user")),
                ("case", models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name="events", to="club_finance.ffpfederationreviewcase")),
            ],
            options={"ordering": ["created_at", "id"], "indexes": [models.Index(fields=["case", "created_at"], name="cf_reg_case_event_idx")]},
        ),
    ]
