from django.db import models
from django.conf import settings
from django.utils import timezone
import secrets
import time
from apps.core.uploads import tenant_upload_path


def uuid7() -> str:
    """Generate a UUID v7 (time-ordered UUID)."""
    nanoseconds = time.time_ns()
    uuid_int = (nanoseconds << 16) | secrets.randbits(48)
    return f"{uuid_int:032x}"


class Contact(models.Model):
    """Contact/person records. Canonical Person table — links to User if person is staff."""
    id = models.UUIDField(primary_key=True, default=uuid7, editable=False)
    organization = models.ForeignKey("companies.Organization", on_delete=models.CASCADE, related_name="contacts")
    # If this Contact represents a staff member, user is set. External contacts leave it null.
    user = models.OneToOneField(
        settings.AUTH_USER_MODEL,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="contact_profile",
    )
    name = models.CharField(max_length=255)
    email = models.EmailField(blank=True)
    phone = models.CharField(max_length=20, blank=True)
    type = models.CharField(max_length=20, choices=[
        ("individual", "Individual"),
        ("organization", "Organization"),
    ], default="individual")
    company = models.ForeignKey("companies.Company", on_delete=models.SET_NULL, null=True, blank=True, related_name="contacts")
    position = models.CharField(max_length=100, blank=True)
    address = models.TextField(blank=True)
    notes = models.TextField(blank=True)
    tags = models.JSONField(default=list)
    avatar = models.ImageField(upload_to=tenant_upload_path("contact-avatars"), null=True, blank=True)
    visibility = models.CharField(
        max_length=10,
        choices=[("public", "Public"), ("private", "Private")],
        default="public",
        help_text="Private contacts only visible to creator.",
    )
    is_favorite = models.BooleanField(default=False)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = "contacts"
        ordering = ["name"]

    def __str__(self):
        return self.name


class Reminder(models.Model):
    """Follow-up reminders attached to a contact."""
    id = models.UUIDField(primary_key=True, default=uuid7, editable=False)
    contact = models.ForeignKey(Contact, on_delete=models.CASCADE, related_name="reminders")
    note = models.CharField(max_length=255)
    remind_at = models.DateTimeField()
    status = models.CharField(
        max_length=10,
        choices=[("pending", "Pending"), ("done", "Done"), ("snoozed", "Snoozed")],
        default="pending",
    )
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = "contact_reminders"
        ordering = ["remind_at"]

    def __str__(self):
        return f"{self.contact.name} — {self.note}"


class Note(models.Model):
    """Free-form note, optionally linked to a contact/company by name."""
    id = models.UUIDField(primary_key=True, default=uuid7, editable=False)
    organization = models.ForeignKey("companies.Organization", on_delete=models.CASCADE, related_name="notes")
    title = models.CharField(max_length=255)
    body = models.TextField(blank=True)
    contact = models.CharField(max_length=255, blank=True)
    company = models.CharField(max_length=255, blank=True)
    tags = models.JSONField(default=list)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = "contact_notes"
        ordering = ["-created_at"]

    def __str__(self):
        return self.title