# ============================================================
# ADDITIVE: Candidate registration + auto-save drafts
#
# The HR/Admin "candidate link" already exists (models_portal.CandidatePortalLink).
# These two NEW tables add:
#   * CandidatePortalAccount - the candidate registers (email + password) through the link
#     and logs back in later to continue where they stopped.
#   * CandidatePortalDraft   - every form step is auto-saved (even half filled / not yet valid)
#     so nothing is lost when the browser closes.  Drafts are committed into the real
#     candidate rows (EmployeeDT, CandidateEducation ...) that HR / Admin already read.
# 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
from .models_portal import CandidatePortalLink


class CandidatePortalAccount(AuditMixin):
    company = models.ForeignKey(company_details, on_delete=models.CASCADE, related_name="candidate_portal_accounts")
    candidate = models.OneToOneField(EmployeeDT, on_delete=models.CASCADE, related_name="portal_account")
    link = models.ForeignKey(CandidatePortalLink, null=True, blank=True, on_delete=models.SET_NULL,
                             related_name="accounts")
    email = models.CharField(max_length=254, db_index=True)
    password = models.CharField(max_length=128)                 # django hasher output, never plain text
    registered_at = models.DateTimeField(auto_now_add=True)
    last_login_at = models.DateTimeField(null=True, blank=True)
    failed_attempts = models.PositiveSmallIntegerField(default=0)
    locked_until = models.DateTimeField(null=True, blank=True)

    class Meta:
        ordering = ["-id"]


class CandidatePortalDraft(AuditMixin):
    company = models.ForeignKey(company_details, on_delete=models.CASCADE, related_name="candidate_portal_drafts")
    candidate = models.ForeignKey(EmployeeDT, on_delete=models.CASCADE, related_name="portal_drafts")
    step = models.CharField(max_length=40)          # profile / career / education / experience / documents / custom
    data = models.JSONField(default=dict, blank=True)
    client_version = models.PositiveIntegerField(default=0)    # browser's counter, to ignore out-of-order saves

    class Meta:
        ordering = ["step"]
        unique_together = (("candidate", "step"),)
