from decimal import Decimal

from django.db import models

from core.models import TimeStampedModel


class WebsiteProject(TimeStampedModel):
    class Status(models.TextChoices):
        QUOTE = "quote", "Em orçamento"
        APPROVED = "approved", "Aprovado"
        DEVELOPMENT = "development", "Em desenvolvimento"
        REVIEW = "review", "Em revisão / testes"
        WAITING = "waiting", "A aguardar cliente"
        ON_HOLD = "on_hold", "Em pausa"
        DELIVERED = "delivered", "Entregue"
        PAID = "paid", "Pago"
        PARTIAL = "partial", "Parcialmente pago"
        MAINTENANCE = "maintenance", "Em manutenção"
        CANCELLED = "cancelled", "Cancelado"
        ARCHIVED = "archived", "Arquivado"

    client = models.ForeignKey("clients.Client", on_delete=models.PROTECT, related_name="website_projects", verbose_name="Cliente")
    title = models.CharField("Projeto", max_length=180)
    primary_domain = models.ForeignKey(
        "domains.Domain", on_delete=models.SET_NULL, null=True, blank=True, related_name="website_projects", verbose_name="Domínio principal"
    )
    recurring_services = models.ManyToManyField(
        "services.Service", blank=True, related_name="website_projects", verbose_name="Serviços recorrentes associados"
    )
    status = models.CharField("Estado", max_length=20, choices=Status.choices, default=Status.QUOTE, db_index=True)
    start_date = models.DateField("Data de início", null=True, blank=True)
    delivery_date = models.DateField("Data de entrega", null=True, blank=True)
    contracted_value = models.DecimalField("Valor contratado", max_digits=12, decimal_places=2, default=Decimal("0.00"))
    historical_received_value = models.DecimalField("Valor recebido (histórico)", max_digits=12, decimal_places=2, default=Decimal("0.00"))
    partner = models.CharField("Parceiro", max_length=150, blank=True)
    theme_name = models.CharField("Tema / template", max_length=150, blank=True)
    technology = models.CharField("Tecnologia", max_length=150, blank=True, help_text="Ex.: WordPress, Django, HTML/CSS")
    repository_reference = models.CharField("Referência do repositório", max_length=250, blank=True)
    notes = models.TextField("Observações", blank=True)

    class Meta:
        verbose_name = "Projeto web"
        verbose_name_plural = "Projetos web"
        ordering = ["-start_date", "title"]

    @property
    def historical_outstanding_value(self):
        return self.contracted_value - self.historical_received_value

    def __str__(self):
        return self.title
