# Tests for the additive Candidate Portal (no-login details + document link).
#   python manage.py test Recruitment.tests_portal
from datetime import timedelta

from django.core import mail
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import TestCase, override_settings
from django.utils import timezone
from rest_framework.test import APIClient

from Employee.models import EmployeeDocument, EmployeeDT
from Recruitment.models import DocumentReview, CandidateProfile
from Recruitment.models_portal import CandidatePortalActivity, CandidatePortalLink
from Recruitment.tests_hiring_plus import Base, _n, valid_aadhaar

PDF = b"%PDF-1.4\n1 0 obj<<>>endobj\ntrailer<<>>\n%%EOF"
PNG = b"\x89PNG\r\n\x1a\n" + b"0" * 32
L = "/api/recruitment/hiring-plus/candidate-links/"


def pdf(name="a.pdf", data=PDF):
    return SimpleUploadedFile(name, data, content_type="application/pdf")


@override_settings(CANDIDATE_PORTAL_BASE_URL="https://app.example.com",
                   EMAIL_BACKEND="django.core.mail.backends.locmem.EmailBackend")
class PortalTests(Base):
    def invite(self, **extra):
        _n[0] += 1
        body = {"name": "Anita Rao", "email": f"anita{_n[0]}@x.com", "phone_number": "9876543210",
                "applied_position": "Dev", "send_email": True}
        body.update(extra)
        r = self.maker.post(L, body, format="json")
        self.assertEqual(r.status_code, 201, r.content)
        d = r.json()["data"]
        return d, f"/api/recruitment/hiring-plus/public/portal/{d['frontend_path'].rsplit('/', 1)[1]}/", r

    def anon(self):
        return APIClient()

    # ---------- HR creates the link ----------
    def test_hr_invites_new_candidate_and_email_goes_out(self):
        d, url, r = self.invite()
        self.assertTrue(r.json()["email_sent"])
        self.assertIn("https://app.example.com/candidate-portal/", mail.outbox[0].body)
        c = EmployeeDT.objects.get(pk=d["candidate"])
        self.assertEqual((c.candidate_status, c.Employee_Status, c.is_active, c.application_submitted),
                         ("APPLIED", "Candidate", False, False))
        self.assertEqual(d["status"], "Not opened")
        # shows up in the normal HR candidate list
        rows = self.maker.get("/api/recruitment/candidates/").json()["data"]
        self.assertIn(c.id, [x["id"] for x in rows])

    def test_link_for_existing_candidate_and_old_link_dies(self):
        cand = self.mk_candidate()
        r1 = self.maker.post(L, {"candidate": cand["id"]}, format="json").json()["data"]
        r2 = self.maker.post(L, {"candidate": cand["id"], "document_types": ["pan", "BANK"]}, format="json").json()["data"]
        self.assertEqual(r2["document_types"], ["PAN", "BANK"])
        old = f"/api/recruitment/hiring-plus/public/portal/{r1['frontend_path'].rsplit('/', 1)[1]}/"
        self.assertEqual(self.anon().get(old).status_code, 410)

    def test_validation_and_permissions(self):
        self.assertEqual(self.maker.post(L, {"candidate": 99999}, format="json").status_code, 404)
        self.assertEqual(self.maker.post(L, {"name": "X"}, format="json").status_code, 400)
        bad = self.maker.post(L, {"name": "X", "email": "x@y.com", "document_types": ["OFFER_LETTER"]}, format="json")
        self.assertEqual(bad.status_code, 400)
        self.assertFalse(EmployeeDT.objects.filter(email="x@y.com").exists())      # nothing half-created
        self.assertIn(self.anon().get(L).status_code, (401, 403))
        self.assertIn(self.anon().post(L, {}, format="json").status_code, (401, 403))

    # ---------- candidate (no login) ----------
    def test_public_get_needs_no_login_and_bad_tokens(self):
        d, url, _ = self.invite()
        r = self.anon().get(url)
        self.assertEqual(r.status_code, 200, r.content)
        data = r.json()["data"]
        self.assertEqual(data["candidate"]["name"], "Anita Rao")
        self.assertNotIn("hike", str(data).lower())
        self.assertEqual(self.anon().get("/api/recruitment/hiring-plus/public/portal/bogus/").status_code, 404)
        CandidatePortalLink.objects.update(expires_at=timezone.now() - timedelta(minutes=1))
        self.assertEqual(self.anon().get(url).status_code, 410)

    def test_profile_add_and_update_reaches_hr_screens(self):
        d, url, _ = self.invite()
        a = self.anon()
        aad = valid_aadhaar()
        r = a.patch(url, {"date_of_birth": "1995-04-12", "gender": "Female", "current_address": "12 MG Road",
                          "permanent_address": "Village Road", "aadhaar_number": aad, "pan_number": "ABCPE1234F",
                          "personal_email": "anita.p@gmail.com", "notice_period_days": 60, "current_ctc_lpa": 6,
                          "expected_ctc_lpa": 8.5, "current_company": "Acme"}, format="json")
        self.assertEqual(r.status_code, 200, r.content)
        self.assertNotIn(aad, r.content.decode())                     # full Aadhaar never comes back
        self.assertEqual(r.json()["data"]["profile"]["aadhaar_masked"], "XXXX XXXX " + aad[-4:])
        # update again (candidate changes his mind)
        r = a.patch(url, {"current_address": "99 New Street", "expected_ctc_lpa": 9}, format="json")
        self.assertEqual(r.json()["data"]["profile"]["current_address"], "99 New Street")
        # HR sees the same data in the normal candidate detail
        det = self.maker.get(f"/api/recruitment/candidates/{d['candidate']}/").json()["data"]
        self.assertEqual(det["expected_ctc_lpa"], 9.0)
        self.assertEqual(det["current_ctc_lpa"], 6.0)
        c = EmployeeDT.objects.get(pk=d["candidate"])
        self.assertEqual((c.Current_Address, c.pan_number), ("99 New Street", "ABCPE1234F"))
        self.assertEqual(CandidateProfile.objects.get(candidate=c).notice_period_days, 60)
        acts = list(CandidatePortalActivity.objects.filter(candidate=c).values_list("action", flat=True))
        self.assertEqual(acts.count("PROFILE_UPDATED"), 2)
        self.assertNotIn(aad, str(list(CandidatePortalActivity.objects.values_list("detail", flat=True))))

    def test_bad_values_rejected(self):
        _, url, _ = self.invite()
        a = self.anon()
        for body in ({"date_of_birth": "2999-01-01"}, {"aadhaar_number": "123456789012"}, {"pan_number": "abc"},
                     {"personal_email": "nope"}, {"notice_period_days": 45}, {"expected_ctc_lpa": 5000},
                     {"phone_number": "12"}, {"current_address": "x" * 600}):
            self.assertEqual(a.patch(url, body, format="json").status_code, 400, body)

    def test_cannot_touch_hr_fields(self):
        d, url, _ = self.invite()
        self.anon().patch(url, {"candidate_status": "SELECTED", "email": "evil@x.com", "name": "Hacker",
                                "is_active": True, "recruiter": "x"}, format="json")
        c = EmployeeDT.objects.get(pk=d["candidate"])
        self.assertEqual((c.candidate_status, c.name, c.is_active), ("APPLIED", "Anita Rao", False))
        self.assertNotEqual(c.email, "evil@x.com")

    def test_education_and_experience_crud(self):
        d, url, _ = self.invite()
        a = self.anon()
        e = a.post(url + "education/", {"highest_qualification": "B.Tech", "university_board": "Pune Univ",
                                        "passing_year": 2017}, format="json")
        self.assertEqual(e.status_code, 201, e.content)
        eid = e.json()["data"]["id"]
        self.assertEqual(a.patch(url + f"education/{eid}/", {"percentage_cgpa": "8.1"}, format="json").status_code, 200)
        self.assertEqual(a.post(url + "education/", {"passing_year": 1800}, format="json").status_code, 400)
        x = a.post(url + "experience/", {"company_name": "Acme", "designation": "Dev",
                                         "start_date": "2018-01-01", "end_date": "2021-01-01"}, format="json")
        self.assertEqual(x.status_code, 201, x.content)
        self.assertEqual(a.post(url + "experience/", {"company_name": "B", "start_date": "2021-02-01",
                                                      "end_date": "2020-01-01"}, format="json").status_code, 400)
        snap = a.get(url).json()["data"]
        self.assertEqual(len(snap["education"]), 1)
        self.assertEqual(snap["education"][0]["percentage_cgpa"], "8.1")
        self.assertAlmostEqual(snap["career"]["total_experience_years"], 3.0, delta=0.2)    # synced for HR (same maths HR already uses)
        self.assertEqual(a.delete(url + f"education/{eid}/").status_code, 200)
        self.assertEqual(a.get(url).json()["data"]["education"], [])

    def test_cannot_touch_another_candidates_rows(self):
        _, url1, _ = self.invite()
        d2, url2, _ = self.invite()
        a = self.anon()
        eid = a.post(url2 + "education/", {"highest_qualification": "MBA"}, format="json").json()["data"]["id"]
        self.assertEqual(a.patch(url1 + f"education/{eid}/", {"highest_qualification": "x"}, format="json").status_code, 404)
        self.assertEqual(a.delete(url1 + f"education/{eid}/").status_code, 404)

    # ---------- documents ----------
    def test_document_upload_replace_delete(self):
        d, url, _ = self.invite()
        a = self.anon()
        r = a.post(url + "documents/", {"document_type": "RESUME", "file": pdf("cv.pdf")}, format="multipart")
        self.assertEqual(r.status_code, 201, r.content)
        first = r.json()["data"]["id"]
        # uploading a single-type document again replaces the old one
        r = a.post(url + "documents/", {"document_type": "RESUME", "file": pdf("cv2.pdf")}, format="multipart")
        self.assertTrue(r.json()["replaced"])
        c = EmployeeDT.objects.get(pk=d["candidate"])
        self.assertFalse(EmployeeDocument.objects.get(pk=first).is_active)
        self.assertEqual(EmployeeDocument.objects.filter(employee=c, document_type="RESUME", is_active=True).count(), 1)
        self.assertTrue(c.resume)                                                         # mirrored for the HR card
        new = r.json()["data"]["id"]
        # PUT = replace this exact document
        r = a.put(url + f"documents/{new}/", {"file": pdf("cv3.pdf")}, format="multipart")
        self.assertEqual(r.status_code, 200, r.content)
        newer = r.json()["data"]["id"]
        # EDUCATION allows several
        for i in range(2):
            a.post(url + "documents/", {"document_type": "EDUCATION", "file": pdf(f"e{i}.pdf")}, format="multipart")
        self.assertEqual(EmployeeDocument.objects.filter(employee=c, document_type="EDUCATION", is_active=True).count(), 2)
        self.assertEqual(a.delete(url + f"documents/{newer}/").status_code, 200)
        self.assertFalse(EmployeeDocument.objects.filter(employee=c, document_type="RESUME", is_active=True).exists())

    def test_document_validation(self):
        _, url, _ = self.invite()
        a = self.anon()
        post = lambda t, f: a.post(url + "documents/", {"document_type": t, "file": f}, format="multipart")
        self.assertEqual(post("RESUME", SimpleUploadedFile("x.exe", b"MZ....")).status_code, 400)
        self.assertEqual(post("PAN", SimpleUploadedFile("pan.pdf", b"<html>not a pdf</html>")).status_code, 400)  # magic bytes
        self.assertEqual(post("PAN", SimpleUploadedFile("pan.pdf", b"")).status_code, 400)
        self.assertEqual(post("OFFER_LETTER", pdf()).status_code, 400)                       # HR-only type
        self.assertEqual(post("PAN", SimpleUploadedFile("pan.png", PNG)).status_code, 201)
        self.assertEqual(post("RESUME", SimpleUploadedFile("cv.docx", b"PK\x03\x04" + b"0" * 20)).status_code, 201)
        self.assertEqual(post("PAN", SimpleUploadedFile("big.pdf", PDF + b"0" * (10 * 1024 * 1024))).status_code, 400)

    def test_verified_document_is_frozen_and_rejection_reason_visible(self):
        d, url, _ = self.invite()
        a = self.anon()
        doc_id = a.post(url + "documents/", {"document_type": "PAN", "file": pdf()}, format="multipart").json()["data"]["id"]
        rv = DocumentReview.objects.get(document_id=doc_id)
        rv.status, rv.remarks = "Rejected", "Photo is blurry"
        rv.save()
        row = [x for x in a.get(url).json()["data"]["documents"] if x["id"] == doc_id][0]
        self.assertEqual((row["status"], row["reject_reason"]), ("Rejected", "Photo is blurry"))
        again = a.put(url + f"documents/{doc_id}/", {"file": pdf("pan2.pdf")}, format="multipart")
        self.assertEqual(again.status_code, 200)
        new_id = again.json()["data"]["id"]
        self.assertEqual(again.json()["data"]["status"], "Pending")                         # back to HR review
        rv = DocumentReview.objects.get(document_id=new_id)
        rv.status = "Verified"
        rv.save()
        self.assertEqual(a.put(url + f"documents/{new_id}/", {"file": pdf()}, format="multipart").status_code, 403)
        self.assertEqual(a.delete(url + f"documents/{new_id}/").status_code, 403)
        self.assertEqual(a.post(url + "documents/", {"document_type": "PAN", "file": pdf()}, format="multipart").status_code, 403)

    def test_requested_documents_and_checklist(self):
        cand = self.mk_candidate()
        d = self.maker.post(L, {"candidate": cand["id"], "document_types": ["BANK"]}, format="json").json()["data"]
        url = f"/api/recruitment/hiring-plus/public/portal/{d['frontend_path'].rsplit('/', 1)[1]}/"
        snap = self.anon().get(url).json()["data"]
        self.assertEqual([x["code"] for x in snap["requested_documents"]], ["BANK"])
        self.assertIn("BANK", [m["field"] for m in snap["progress"]["missing"]])

    # ---------- submit ----------
    def test_submit_flow_and_hr_status(self):
        d, url, _ = self.invite()
        a = self.anon()
        r = a.post(url + "submit/", {}, format="json")
        self.assertEqual(r.status_code, 400)
        self.assertEqual(r.json()["code"], "INCOMPLETE")
        self.assertTrue(len(r.json()["errors"]) >= 4)
        a.patch(url, {"date_of_birth": "1995-04-12", "gender": "Female", "current_address": "A",
                      "same_as_current_address": True}, format="json")
        a.post(url + "education/", {"highest_qualification": "B.Com"}, format="json")
        a.post(url + "documents/", {"document_type": "RESUME", "file": pdf()}, format="multipart")
        # give the candidate's recruiter an e-mail so the heads-up goes out
        mail.outbox.clear()
        ok = a.post(url + "submit/", {}, format="json")
        self.assertEqual(ok.status_code, 200, ok.content)
        self.assertEqual(ok.json()["data"]["progress"]["percent"], 100)
        c = EmployeeDT.objects.get(pk=d["candidate"])
        self.assertTrue(c.application_submitted)
        row = self.maker.get(L, {"candidate": c.id}).json()["data"][0]
        self.assertEqual((row["status"], row["submit_count"]), ("Submitted", 1))
        # candidate edits after submitting -> HR is told
        a.patch(url, {"current_address": "B"}, format="json")
        self.assertEqual(self.maker.get(L, {"candidate": c.id}).json()["data"][0]["status"], "Updated after submit")
        acts = self.maker.get(f"{L}{row['id']}/activity/").json()["data"]
        self.assertIn("SUBMITTED", [x["action"] for x in acts])

    # ---------- locks ----------
    def test_compensation_locks_after_selection_and_closed_is_read_only(self):
        d, url, _ = self.invite()
        a = self.anon()
        self.assertEqual(a.patch(url, {"expected_ctc_lpa": 7}, format="json").status_code, 200)
        EmployeeDT.objects.filter(pk=d["candidate"]).update(candidate_status="SELECTED")
        self.assertEqual(a.patch(url, {"expected_ctc_lpa": 20}, format="json").status_code, 403)
        self.assertEqual(a.patch(url, {"current_address": "ok still editable"}, format="json").status_code, 200)
        self.assertIn("compensation", a.get(url).json()["data"]["link"]["locked_sections"])
        EmployeeDT.objects.filter(pk=d["candidate"]).update(candidate_status="REJECTED")
        self.assertEqual(a.get(url).status_code, 200)
        self.assertFalse(a.get(url).json()["data"]["link"]["editable"])
        self.assertEqual(a.patch(url, {"current_address": "x"}, format="json").status_code, 403)
        self.assertEqual(a.post(url + "documents/", {"document_type": "PAN", "file": pdf()}, format="multipart").status_code, 403)

    def test_verified_aadhaar_is_frozen(self):
        from Recruitment.models_plus import IdentityVerification
        d, url, _ = self.invite()
        a = self.anon()
        aad = valid_aadhaar()
        self.assertEqual(a.patch(url, {"aadhaar_number": aad}, format="json").status_code, 200)
        c = EmployeeDT.objects.get(pk=d["candidate"])
        IdentityVerification.objects.create(company=c.company, candidate=c, id_type="AADHAAR", status="Verified")
        other = valid_aadhaar("34567890123")
        self.assertEqual(a.patch(url, {"aadhaar_number": other}, format="json").status_code, 403)
        self.assertEqual(a.patch(url, {"aadhaar_number": aad, "gender": "Male"}, format="json").status_code, 200)

    def test_revoke(self):
        d, url, _ = self.invite()
        self.assertEqual(self.maker.post(f"{L}{d['id']}/revoke/", {}, format="json").status_code, 200)
        self.assertEqual(self.anon().get(url).status_code, 410)
        self.assertEqual(self.anon().patch(url, {"gender": "x"}, format="json").status_code, 410)
