from django.db import models


class Client(models.Model):
    name = models.CharField(max_length=255, unique=True)
    email = models.EmailField(blank=True, null=True)
    phone = models.CharField(max_length=20, blank=True, null=True)
    website = models.URLField(blank=True, null=True)
    description = models.TextField(blank=True, null=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

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

    def __str__(self):
        return self.name


class CompanyLinkedInConfig(models.Model):
    """Per-company (client) LinkedIn posting credentials. When a JD is posted to
    LinkedIn, the JD's client config is used first; otherwise the global token."""
    client = models.OneToOneField(
        Client, on_delete=models.CASCADE, related_name="linkedin_config"
    )
    access_token = models.TextField(blank=True, default="")
    author_urn = models.CharField(
        max_length=120, blank=True, default="",
        help_text="urn:li:organization:<id> (or urn:li:person:<id>)",
    )
    oauth_client_id = models.CharField(max_length=120, blank=True, default="")
    oauth_client_secret = models.CharField(max_length=255, blank=True, default="")
    is_active = models.BooleanField(default=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = "company_linkedin_config"

    def __str__(self):
        return f"LinkedIn config for {self.client.name}"

    _PREFIX = "enc::"

    def save(self, *args, **kwargs):
        # Encrypt secrets at rest (skip if already encrypted or blank).
        from apps.llm.crypto import encrypt_key
        for f in ("access_token", "oauth_client_secret"):
            v = getattr(self, f, "") or ""
            if v and not v.startswith(self._PREFIX):
                setattr(self, f, encrypt_key(v))
        super().save(*args, **kwargs)

    def get_access_token(self) -> str:
        from apps.llm.crypto import decrypt_key
        return decrypt_key(self.access_token)

    def get_oauth_client_secret(self) -> str:
        from apps.llm.crypto import decrypt_key
        return decrypt_key(self.oauth_client_secret)
