# ============================================================
# ADDITIVE: Candidate Portal (no-login "fill your details" link)
#
# HR / Admin sends a private link. The candidate opens it WITHOUT login,
# fills / updates every detail (personal, address, education, experience,
# expected CTC, notice period) and uploads / replaces documents.
# HR sees the same data in the normal candidate screens, runs interviews,
# and the same EmployeeDT row later becomes the employee.
#
# Both tables are NEW. Imported at the bottom of Recruitment/models.py.
# ============================================================
from django.db import models

from Company.models import company_details
from Employee.models import EmployeeDT

from .models import AuditMixin


class CandidatePortalLink(AuditMixin):
    company = models.ForeignKey(company_details, on_delete=models.CASCADE, related_name="candidate_portal_links")
    candidate = models.ForeignKey(EmployeeDT, on_delete=models.CASCADE, related_name="portal_links")
    token = models.CharField(max_length=80, unique=True)
    document_types = models.JSONField(default=list, blank=True)     # documents HR specially asks for
    expires_at = models.DateTimeField()
    revoked = models.BooleanField(default=False)
    sent_to = models.CharField(max_length=254, blank=True, null=True)
    first_opened_at = models.DateTimeField(null=True, blank=True)
    last_opened_at = models.DateTimeField(null=True, blank=True)
    last_edit_at = models.DateTimeField(null=True, blank=True)      # last time the candidate changed anything
    submitted_at = models.DateTimeField(null=True, blank=True)      # last time the candidate pressed "Submit"
    submit_count = models.PositiveIntegerField(default=0)

    class Meta:
        ordering = ["-created_at"]


class CandidatePortalActivity(AuditMixin):
    """Append-only trail of what the (unauthenticated) candidate changed. Values of sensitive
    fields (Aadhaar / PAN / bank) are NEVER stored here - only the field names."""
    company = models.ForeignKey(company_details, on_delete=models.CASCADE, related_name="candidate_portal_activity")
    candidate = models.ForeignKey(EmployeeDT, on_delete=models.CASCADE, related_name="portal_activity")
    link = models.ForeignKey(CandidatePortalLink, null=True, blank=True, on_delete=models.SET_NULL,
                             related_name="activity")
    action = models.CharField(max_length=30, db_index=True)
    detail = models.JSONField(default=dict, blank=True)
    ip_address = models.CharField(max_length=64, blank=True, null=True)

    class Meta:
        ordering = ["-id"]
