from decimal import Decimal

from django.contrib.auth.models import User
from django.test import TestCase
from django.urls import reverse

from Company.models import company_details
from Employee.models import Candidate, EmployeeAccount, EmployeeDT
from Recruitment.models import CandidateProfile, Offer

from .models import SuperAdminProfile


def mk_company(n, name):
    return company_details.objects.create(
        email=f"c{n}@x.com", contact_no=f"90000000{n:02d}", password="pw",
        Registered_Company_Name=name, Brand_Name=name + " Brand", status=True, is_verified=True,
    )


def mk_emp(company, name, **kw):
    d = dict(company=company, name=name, email=f"{name.lower().replace(' ', '')}@x.com",
             Job_Title="Dev", password="pw")
    d.update(kw)
    return EmployeeDT.objects.create(**d)


class B2BCompanyWise(TestCase):
    def setUp(self):
        u = User.objects.create_user(username="sa", email="sa@x.com", password="pw-12345-x")
        SuperAdminProfile.objects.create(user=u, full_name="SA", email="sa@x.com")
        self.client.force_login(u)

        self.a = mk_company(1, "Alpha")
        self.b = mk_company(2, "Beta")

        # ---- Alpha: 2 real employees (1 with login), candidates in several stages ----
        e1 = mk_emp(self.a, "Emp One", is_active=True, candidate_status="")
        EmployeeAccount.objects.create(employee=e1)
        mk_emp(self.a, "Emp Two", is_active=False, candidate_status="")

        c1 = mk_emp(self.a, "Cand One", Employee_Status="Candidate", is_active=False,
                    applied_position="QA", candidate_status="APPLIED")
        mk_emp(self.a, "Cand Two", Employee_Status="Candidate", is_active=False,
               applied_position="QA", candidate_status="FEEDBACK_PENDING")
        mk_emp(self.a, "Cand Three", Employee_Status="Candidate", is_active=False,
               applied_position="QA", candidate_status="REJECTED")
        joined = mk_emp(self.a, "Cand Joined", Employee_Status="Activate", is_active=True,
                        applied_position="Dev", candidate_status="JOINED")
        EmployeeAccount.objects.create(employee=joined)

        Offer.objects.create(company=self.a, offer_id="OFF-1", candidate=c1,
                             offered_ctc_lpa=Decimal("6.5"), status="Accepted")
        Offer.objects.create(company=self.a, offer_id="OFF-2", candidate=c1,
                             offered_ctc_lpa=Decimal("7"), status="Sent")

        # SuperAdmin-table candidate for Alpha + a sync-copy that must NOT be double counted
        Candidate.objects.create(company=self.a, name="SA Cand", email="sa1@x.com", candidate_status="OFFERED")
        Candidate.objects.create(company=self.a, name="Copy", email="copy@x.com",
                                 candidate_status="APPLIED", notes="Legacy EmployeeDT ID: 99")

        # ---- Beta: 1 candidate only, no employees ----
        mk_emp(self.b, "Beta Cand", Employee_Status="Candidate", is_active=False,
               applied_position="HR", candidate_status="SHORTLISTED")

    def row(self, name):
        r = self.client.get(reverse("superadmin_b2b_api"))
        self.assertEqual(r.status_code, 200)
        data = r.json()
        return data, next(c for c in data["companies"] if c["name"].startswith(name))

    def test_company_wise_counts(self):
        data, a = self.row("Alpha")
        # employees = Emp One, Emp Two, Cand Joined (pending candidates excluded)
        self.assertEqual(a["employees_total"], 3)
        self.assertEqual(a["employees_active"], 2)
        self.assertEqual(a["employees_with_login"], 2)
        # candidates: 4 recruitment (Applied, FeedbackPending, Rejected, Joined) + 1 SA-added, copy skipped
        self.assertEqual(a["candidates_total"], 5)
        self.assertEqual(a["buckets"]["applied"], 1)
        self.assertEqual(a["buckets"]["interview"], 1)
        self.assertEqual(a["buckets"]["rejected"], 1)
        self.assertEqual(a["buckets"]["joined"], 1)
        self.assertEqual(a["buckets"]["offer"], 1)          # OFFERED -> OFFER_SENT
        self.assertEqual(a["candidates_in_pipeline"], 3)
        self.assertEqual(a["offers_total"], 2)
        self.assertEqual(a["offers_accepted"], 1)

        _, b = self.row("Beta")
        self.assertEqual(b["employees_total"], 0)
        self.assertEqual(b["candidates_total"], 1)
        self.assertEqual(b["buckets"]["shortlisted"], 1)

        # company isolation: totals are the sum of both companies
        self.assertEqual(data["totals"]["candidates_total"], 6)

    def test_pages_render(self):
        r = self.client.get(reverse("superadmin_b2b_overview"))
        self.assertEqual(r.status_code, 200)
        self.assertContains(r, "Alpha")
        self.assertContains(r, "Beta")
        self.assertNotContains(r, "Alpha Brand")   # company name, not brand
        for tab in ("candidates", "employees", "offers"):
            r = self.client.get(reverse("superadmin_b2b_company", args=[self.a.pk]), {"tab": tab})
            self.assertEqual(r.status_code, 200, tab)
        r = self.client.get(reverse("superadmin_b2b_company", args=[self.a.pk]),
                            {"tab": "candidates", "stage": "interview"})
        self.assertContains(r, "Cand Two")
        self.assertNotContains(r, "Cand One")
        # company isolation on the detail page
        self.assertNotContains(r, "Beta Cand")

    def test_export_and_company_filter(self):
        r = self.client.get(reverse("superadmin_b2b_export"))
        self.assertEqual(r.status_code, 200)
        self.assertIn("Alpha,", r.content.decode())
        data = self.client.get(reverse("superadmin_b2b_api"), {"company": self.b.pk}).json()
        self.assertEqual(len(data["companies"]), 1)

    def test_old_company_detail_no_longer_crashes(self):
        r = self.client.get(reverse("superadmin_company_detail", args=[str(self.a.pk)]))
        self.assertEqual(r.status_code, 200)

    def test_requires_superadmin(self):
        self.client.logout()
        r = self.client.get(reverse("superadmin_b2b_overview"))
        self.assertEqual(r.status_code, 302)


class ExistingPagesShowFullData(B2BCompanyWise):
    """The 3 existing pages: candidates / employees / companies."""

    def test_candidates_page_shows_company_wise_pipeline(self):
        r = self.client.get(reverse("superadmin_candidates"))
        self.assertEqual(r.status_code, 200)
        for n in ("Cand One", "Cand Two", "Cand Three", "Cand Joined", "Beta Cand", "SA Cand"):
            self.assertContains(r, n)
        self.assertNotContains(r, ">Copy<")           # sync copy not shown twice
        # company NAME (registered) is shown, not the brand
        self.assertContains(r, "Alpha")
        self.assertNotContains(r, "Alpha Brand")
        # company filter + stage filter
        r = self.client.get(reverse("superadmin_candidates"), {"company": self.b.pk})
        self.assertContains(r, "Beta Cand")
        self.assertNotContains(r, "Cand One")
        r = self.client.get(reverse("superadmin_candidates"), {"status": "FEEDBACK_PENDING"})
        self.assertContains(r, "Cand Two")
        self.assertNotContains(r, "Cand One")
        # search
        r = self.client.get(reverse("superadmin_candidates"), {"search": "Cand Three"})
        self.assertContains(r, "Cand Three")
        self.assertNotContains(r, "Beta Cand")
        # status dropdown is now populated
        self.assertContains(r, 'value="FEEDBACK_PENDING"')

    def test_employees_page_candidates(self):
        # default list = real employees only (unchanged behaviour)
        r = self.client.get(reverse("superadmin_employees"))
        self.assertEqual(r.status_code, 200)
        self.assertContains(r, "Emp One")
        self.assertNotContains(r, "Cand One")
        # candidates filter
        r = self.client.get(reverse("superadmin_employees"), {"status": "candidates"})
        self.assertContains(r, "Cand One")
        self.assertContains(r, "Beta Cand")
        self.assertNotContains(r, "Emp One")
        self.assertNotContains(r, "Cand Joined")      # joined = employee now
        # employees + candidates
        r = self.client.get(reverse("superadmin_employees"), {"status": "all"})
        self.assertContains(r, "Emp One")
        self.assertContains(r, "Cand One")
        # company name shown (not brand); candidate chip present
        self.assertNotContains(r, "Alpha Brand")
        self.assertContains(r, "Candidate")
        # old status filters still work
        r = self.client.get(reverse("superadmin_employees"), {"status": "inactive"})
        self.assertEqual(r.status_code, 200)

    def test_companies_page_name_and_candidates(self):
        r = self.client.get(reverse("superadmin_companies"))
        self.assertEqual(r.status_code, 200)
        html = r.content.decode()
        self.assertIn("Alpha", html)
        self.assertIn("Brand: Alpha Brand", html)     # brand only as small sub-line
        self.assertIn("Candidates:", html)


class CompanyPanelRuleAndDebug(B2BCompanyWise):
    """Candidates WITH a login account (very common in production) must count too,
    and employees who were hired through recruitment are shown as Joined."""

    def test_candidate_with_account_is_counted(self):
        c = mk_emp(self.b, "Beta WithLogin", Employee_Status="Candidate", is_active=False,
                   applied_position="Ops", candidate_status="INTERVIEW")
        EmployeeAccount.objects.create(employee=c)
        _, b = self.row("Beta")
        self.assertEqual(b["buckets"]["interview"], 1)
        self.assertEqual(b["candidates_total"], 2)
        self.assertEqual(b["employees_total"], 0)       # still not an employee

    def test_activated_employee_counts_as_joined_not_applied(self):
        # default candidate_status is APPLIED, but Employee_Status=Activate => hired
        e = mk_emp(self.b, "Beta Hired", Employee_Status="Activate", is_active=True,
                   applied_position="Dev")
        EmployeeAccount.objects.create(employee=e)
        _, b = self.row("Beta")
        self.assertEqual(b["buckets"]["joined"], 1)
        self.assertEqual(b["buckets"]["applied"], 0)
        self.assertEqual(b["employees_total"], 1)
        r = self.client.get(reverse("superadmin_candidates"), {"status": "JOINED"})
        self.assertContains(r, "Beta Hired")

    def test_debug_endpoint(self):
        r = self.client.get(reverse("superadmin_b2b_debug"))
        self.assertEqual(r.status_code, 200)
        d = r.json()
        self.assertEqual(d["companies"], 2)
        self.assertIn("candidates_pending", d)

    def test_templates_are_ascii_safe(self):
        import pathlib
        for n in ("employees.html", "b2b_overview.html", "b2b_company.html"):
            raw = (pathlib.Path(__file__).resolve().parent.parent / "templates" / "superadmin" / n).read_bytes()
            raw.decode("ascii")
