"""Investment and reward models."""

from __future__ import annotations

from decimal import Decimal

from django.core.validators import MinValueValidator
from django.db import models


class Investment(models.Model):
    """Tracks a user's investment and its reward lifecycle."""

    STATUS_PENDING = "pending"
    STATUS_ACTIVE = "active"
    STATUS_COMPLETED = "completed"
    STATUS_CHOICES = [
        (STATUS_PENDING, "Pending"),
        (STATUS_ACTIVE, "Active"),
        (STATUS_COMPLETED, "Completed"),
    ]

    TIER_CHOICES = [
        (1, "Tier 1: ≤ $100"),
        (2, "Tier 2: ≤ $500"),
        (3, "Tier 3: ≤ $1,000"),
        (4, "Tier 4: ≤ $2,000"),
        (5, "Tier 5: ≤ $5,000"),
        (6, "Tier 6: > $5,000"),
    ]

    user = models.ForeignKey(
        "users.User",
        on_delete=models.CASCADE,
        related_name="investments",
    )
    amount = models.DecimalField(
        max_digits=20,
        decimal_places=8,
        validators=[MinValueValidator(Decimal("10.00000000"))],
    )
    tier = models.IntegerField(choices=TIER_CHOICES)
    daily_reward_rate = models.DecimalField(max_digits=5, decimal_places=2)  # e.g., 1.00 for 1%
    duration_days = models.IntegerField()

    status = models.CharField(
        max_length=20,
        choices=STATUS_CHOICES,
        default=STATUS_PENDING,
    )
    start_date = models.DateTimeField()
    end_date = models.DateTimeField()
    
    # ROI tracking fields
    roi_total_amount = models.DecimalField(
        max_digits=20,
        decimal_places=8,
        default=Decimal("0.00000000"),
        help_text="Accumulated total ROI amount generated for this investment"
    )
    roi_total_percent = models.DecimalField(
        max_digits=10,
        decimal_places=4,
        default=Decimal("0.0000"),
        help_text="Accumulated total ROI percentage ((roi_total_amount / amount) * 100)"
    )

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = "investments"
        indexes = [
            models.Index(fields=["user", "status"]),
            models.Index(fields=["status", "end_date"]),
        ]

    def __str__(self) -> str:
        return f"Investment #{self.id} - {self.user.first_name} - ${self.amount}"

    @staticmethod
    def get_tier_info(amount: Decimal | float | int) -> dict[str, Decimal | int]:
        """Determine tier metadata based on investment amount."""
        normalized = Decimal(str(amount))
        if normalized <= Decimal("100"):
            return {"tier": 1, "rate": Decimal("1.00"), "duration": 120}
        if normalized <= Decimal("500"):
            return {"tier": 2, "rate": Decimal("1.50"), "duration": 130}
        if normalized <= Decimal("1000"):
            return {"tier": 3, "rate": Decimal("2.00"), "duration": 140}
        if normalized <= Decimal("2000"):
            return {"tier": 4, "rate": Decimal("2.50"), "duration": 150}
        if normalized <= Decimal("5000"):
            return {"tier": 5, "rate": Decimal("3.00"), "duration": 160}
        return {"tier": 6, "rate": Decimal("3.50"), "duration": 180}


class Reward(models.Model):
    """Daily reward entries tied to investments."""

    investment = models.ForeignKey(
        Investment,
        on_delete=models.CASCADE,
        related_name="rewards",
    )
    amount = models.DecimalField(max_digits=20, decimal_places=8)
    reward_date = models.DateField()
    calculated_at = models.DateTimeField(auto_now_add=True)
    distributed_at = models.DateTimeField(null=True, blank=True)

    class Meta:
        db_table = "rewards"
        unique_together = ["investment", "reward_date"]
        indexes = [
            models.Index(fields=["investment", "reward_date"]),
            models.Index(fields=["reward_date", "distributed_at"]),
        ]

    def __str__(self) -> str:
        return f"Reward {self.reward_date} for investment {self.investment_id}"
