import io
import shutil
import tempfile
from datetime import date
from decimal import Decimal
from pathlib import Path

from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import override_settings
from PIL import Image
from rest_framework.test import APIClient, APITestCase

from apps.accounting.models import Account, Department, EmployeeProfile, LedgerEntry, Voucher
from apps.accounts_rbac.constants import ROLE_PRESETS
from apps.accounts_rbac.models import (
    CompanyMembership,
    ContactVerificationChallenge,
    Device,
    Role,
    StaffAccessCredential,
    User,
    UserAvatar,
    UserSecurityEvent,
)
from apps.hr.models import DepartmentAccessTemplate, EmployeeDetail, StaffProfileChangeRequest
from apps.localization.bs_calendar import bs_to_ad
from apps.projects.models import Project
from apps.tenancy.models import Branch, Company, FiscalYear


class StaffIdentityAndSelfServiceTests(APITestCase):
    def setUp(self):
        self.tmp_dir = tempfile.mkdtemp(prefix="maya_staff_id_")
        self._override = override_settings(PRIVATE_DOCUMENT_ROOT=Path(self.tmp_dir), DEBUG=True)
        self._override.enable()

        self.roles = {}
        for rcode, spec in ROLE_PRESETS.items():
            self.roles[rcode], _ = Role.objects.get_or_create(
                code=rcode,
                defaults={"name": spec["name"], "permissions": spec["permissions"], "is_system": True},
            )

        self.company = Company.objects.create(code="MAYA-HR", name="Maya Builders Pvt Ltd", pan_vat_no="601112223")
        self.branch = Branch.objects.create(company=self.company, code="HO-1", name="Kathmandu HO", is_head_office=True)
        self.fy = FiscalYear.objects.create(
            company=self.company,
            name="2083/84",
            start_date=bs_to_ad(2083, 4, 1),
            end_date=bs_to_ad(2084, 3, 31),
            is_current=True,
        )
        self.fy.generate_nepal_periods(2083)

        self.dept_acc = Department.objects.create(company=self.company, code="FIN", name="Accounts & Finance")
        self.dept_eng = Department.objects.create(company=self.company, code="ENG", name="Engineering")
        self.proj = Project.objects.create(company=self.company, code="PRJ-HR1", name="Bridge Works")

        self.hr_user = User.objects.create_user("hrmanager", "hr@maya.local", "HrPass@1234", full_name="HR Lead")
        CompanyMembership.objects.create(
            user=self.hr_user, company=self.company, role=self.roles["HR_MANAGER"], is_default=True, is_active=True
        )
        self.super_user = User.objects.create_superuser("superhr", "super@maya.local", "SuperPass@123")
        CompanyMembership.objects.create(
            user=self.super_user, company=self.company, role=self.roles["SUPER_ADMIN"], is_default=True, is_active=True
        )

    def tearDown(self):
        self._override.disable()
        shutil.rmtree(self.tmp_dir, ignore_errors=True)

    def _client(self, user):
        c = APIClient()
        c.force_authenticate(user=user)
        return c

    def test_01_to_14_onboarding_six_digit_code_auth_lockout_and_dept_templates(self):
        hr = self._client(self.hr_user)
        sup = self._client(self.super_user)
        headers = {"HTTP_X_COMPANY_ID": str(self.company.id)}

        # Configure Engineering Dept Access Template
        r_tpl = hr.post(
            f"/api/hr/departments/{self.dept_eng.id}/access-template/",
            {
                "default_role_id": str(self.roles["SITE_ENGINEER"].id),
                "default_data_scope": "PROJECT",
                "allowed_project_ids": [str(self.proj.id)],
            },
            format="json",
            **headers,
        )
        self.assertEqual(r_tpl.status_code, 200)
        self.assertEqual(r_tpl.data["default_role_code"], "SITE_ENGINEER")

        # 1-6. Create Staff with automatic User creation + Dept role + unique 6-digit code
        r_create = hr.post(
            "/api/hr/staff/",
            {
                "full_name": "Sita Sharma",
                "email": "sita.sharma@maya.local",
                "mobile_number": "9841000011",
                "department_id": str(self.dept_acc.id),
                "branch_id": str(self.branch.id),
                "designation": "Accounts Officer",
                "create_login": True,
                "password": "StaffPass@123",
            },
            format="json",
            **headers,
        )
        self.assertEqual(r_create.status_code, 201)
        code1 = r_create.data["one_time_staff_code"]
        self.assertRegex(code1, r"^\d{6}$")
        staff_id = r_create.data["staff"]["id"]
        user_id = r_create.data["staff"]["user"]["id"]

        # Ordinary GET never exposes plaintext secret code or hash
        r_get = hr.get(f"/api/hr/staff/{staff_id}/", **headers)
        self.assertEqual(r_get.status_code, 200)
        self.assertEqual(r_get.data["user"]["staff_code_status"]["masked_code"], "******")
        self.assertNotIn(code1, str(r_get.data))

        # Permanent 1:1 duplicate prevention on re-provisioning same employee or duplicate code
        self.assertEqual(
            hr.post(f"/api/hr/staff/{staff_id}/create-login/", {}, format="json", **headers).status_code, 400
        )
        self.assertEqual(
            hr.post(
                "/api/hr/staff/",
                {"full_name": "Dup Emp", "employee_code": r_create.data["staff"]["employee_code"]},
                format="json",
                **headers,
            ).status_code,
            400,
        )

        # Create second staff -> distinct 6-digit code guaranteed via unique HMAC fingerprint
        r_create2 = hr.post(
            "/api/hr/staff/",
            {"full_name": "Hari Thapa", "email": "hari.thapa@maya.local", "department_id": str(self.dept_eng.id), "create_login": True},
            format="json",
            **headers,
        )
        self.assertEqual(r_create2.status_code, 201)
        self.assertNotEqual(code1, r_create2.data["one_time_staff_code"])
        self.assertEqual(r_create2.data["staff"]["user"]["role_code"], "SITE_ENGINEER")

        # 7. Login with email + password works
        anon = APIClient()
        r_pw_login = anon.post("/api/v1/auth/login/", {"identifier": "sita.sharma@maya.local", "password": "StaffPass@123"}, format="json")
        self.assertEqual(r_pw_login.status_code, 200)
        self.assertEqual(r_pw_login.data["staff_employee"]["designation"], "Accounts Officer")

        # 8. Login with username OR email + 6-digit staff code works
        anon2 = APIClient()
        r_code_login = anon2.post("/api/auth/staff-code/login/", {"identifier": "sita.sharma@maya.local", "staff_code": code1}, format="json")
        self.assertEqual(r_code_login.status_code, 200)
        self.assertEqual(r_code_login.data["email"], "sita.sharma@maya.local")

        # 11. Privileged roles (SUPER_ADMIN / COMPANY_ADMIN) cannot use 6-digit code login
        from apps.accounts_rbac.services import StaffCodeGenerationService

        sup_code = StaffCodeGenerationService.generate_and_assign(user=self.super_user)
        r_priv = APIClient().post("/api/auth/staff-code/login/", {"identifier": "superhr", "staff_code": sup_code}, format="json")
        self.assertEqual(r_priv.status_code, 403)

        # 9. Expired / Wrong attempts lock out staff code
        bad_client = APIClient()
        for _ in range(5):
            bad_client.post("/api/auth/staff-code/login/", {"identifier": "sita.sharma@maya.local", "staff_code": "000000"}, format="json")
        r_locked = bad_client.post("/api/auth/staff-code/login/", {"identifier": "sita.sharma@maya.local", "staff_code": code1}, format="json")
        self.assertEqual(r_locked.status_code, 423)

        # Reset staff code invalidates old code cleanly
        r_reset = hr.post(f"/api/hr/staff/{staff_id}/reset-staff-code/", {}, format="json", **headers)
        self.assertEqual(r_reset.status_code, 200)
        new_code = r_reset.data["one_time_staff_code"]
        self.assertEqual(
            APIClient().post("/api/auth/staff-code/login/", {"identifier": "sita.sharma@maya.local", "staff_code": code1}, format="json").status_code,
            401,
        )
        self.assertEqual(
            APIClient().post("/api/auth/staff-code/login/", {"identifier": "sita.sharma@maya.local", "staff_code": new_code}, format="json").status_code,
            200,
        )

        # 12-13. Department transfer impact preview & permission recalculation
        r_prev = hr.post(f"/api/hr/staff/{staff_id}/preview-access-change/", {"department_id": str(self.dept_eng.id)}, format="json", **headers)
        self.assertEqual(r_prev.status_code, 200)
        self.assertEqual(r_prev.data["previous_role"], "ACCOUNTANT")
        self.assertEqual(r_prev.data["new_role"], "SITE_ENGINEER")
        r_app = hr.post(f"/api/hr/staff/{staff_id}/update-access/", {"department_id": str(self.dept_eng.id)}, format="json", **headers)
        self.assertEqual(r_app.status_code, 200)
        self.assertEqual(CompanyMembership.objects.get(user_id=user_id, company=self.company).role.code, "SITE_ENGINEER")

        # 14. Bulk onboarding preview + commit omits staff codes from import output
        r_bprev = hr.post(
            "/api/hr/staff/bulk-preview/",
            {"rows": [{"full_name": "Bulk One", "email": "bulk1@maya.local", "department_code": "ENG", "create_login": True}]},
            format="json",
            **headers,
        )
        self.assertEqual(r_bprev.data["valid_count"], 1)
        r_bimp = hr.post(
            "/api/hr/staff/bulk-import/",
            {"rows": [{"full_name": "Bulk One", "email": "bulk1@maya.local", "department_code": "ENG", "create_login": True}]},
            format="json",
            **headers,
        )
        self.assertEqual(r_bimp.status_code, 201)
        self.assertNotIn("one_time_staff_code", str(r_bimp.data))

    def test_15_to_26_self_service_avatar_email_verify_hr_approval_and_offboarding(self):
        hr = self._client(self.hr_user)
        headers = {"HTTP_X_COMPANY_ID": str(self.company.id)}

        r_staff = hr.post(
            "/api/hr/staff/",
            {
                "full_name": "Ramesh Karki",
                "email": "ramesh@maya.local",
                "department_id": str(self.dept_acc.id),
                "designation": "Junior Accountant",
                "create_login": True,
                "password": "OldPassword@1",
            },
            format="json",
            **headers,
        )
        staff_id = r_staff.data["staff"]["id"]
        staff_code = r_staff.data["one_time_staff_code"]
        user = User.objects.get(id=r_staff.data["staff"]["user"]["id"])
        me_client = self._client(user)

        # 15 & 22. Avatar Upload Validation (rejects non-image executable payload, accepts clean PNG)
        fake_file = SimpleUploadedFile("evil.png", b"<?php echo 'hack'; ?>", content_type="image/png")
        self.assertEqual(me_client.post("/api/profile/avatar/", {"file": fake_file}, format="multipart").status_code, 400)

        img_buf = io.BytesIO()
        Image.new("RGB", (600, 600), color=(30, 64, 175)).save(img_buf, format="PNG")
        valid_png = SimpleUploadedFile("photo.png", img_buf.getvalue(), content_type="image/png")
        r_av = me_client.post("/api/profile/avatar/", {"file": valid_png}, format="multipart")
        self.assertEqual(r_av.status_code, 200)
        self.assertTrue(me_client.get(f"/api/profile/avatar/{user.id}/?thumb=1").status_code == 200)

        # 16. Personal details self-update succeeds while protected fields require HR request
        r_upd = me_client.patch("/api/profile/me/", {"full_name": "Ramesh B. Karki", "province": "Bagmati", "district": "Kathmandu"}, format="json")
        self.assertEqual(r_upd.status_code, 200)
        user.refresh_from_db()
        self.assertEqual(user.full_name, "Ramesh B. Karki")

        # 17. Protected field change request workflow
        r_req = me_client.post("/api/profile/change-requests/", {"field_name": "designation", "requested_value": "Senior Accountant"}, format="json")
        self.assertEqual(r_req.status_code, 201)
        req_id = r_req.data["id"]
        self.assertEqual(hr.post(f"/api/hr/change-requests/{req_id}/approve/", {}, format="json", **headers).status_code, 200)
        emp = EmployeeDetail.objects.get(id=staff_id)
        self.assertEqual(emp.employee_profile.designation, "Senior Accountant")

        # 18. Email change verification via OTP challenge
        r_ver = me_client.post("/api/profile/contact/verify/", {"channel": "EMAIL", "new_contact": "ramesh.new@maya.local"}, format="json")
        self.assertEqual(r_ver.status_code, 200)
        otp = r_ver.data["dev_verification_code"]
        r_conf = me_client.post("/api/profile/contact/update/", {"challenge_id": r_ver.data["challenge_id"], "verification_code": otp}, format="json")
        self.assertEqual(r_conf.status_code, 200)
        user.refresh_from_db()
        self.assertEqual(user.email, "ramesh.new@maya.local")

        # 19. Self change password + change 6-digit code + get status (masked)
        self.assertEqual(me_client.post("/api/profile/change-password/", {"current_password": "OldPassword@1", "new_password": "NewPassword@9"}, format="json").status_code, 200)
        self.assertEqual(me_client.post("/api/profile/change-staff-code/", {"current_password": "NewPassword@9", "new_code": "739204"}, format="json").status_code, 200)
        r_st = me_client.get("/api/profile/staff-code/status/")
        self.assertEqual(r_st.data["masked_code"], "******")
        self.assertNotIn("739204", str(r_st.data))
        self.assertNotIn(staff_code, str(r_st.data))

        # 20 & 26. Termination/Offboarding disables logins, revokes devices, preserves historical vouchers & audit
        acc_cash = Account.objects.create(company=self.company, code="1010", name="Cash", account_type="ASSET")
        v = Voucher.objects.create(
            company=self.company,
            fiscal_year=self.fy,
            fiscal_period=self.fy.periods.first(),
            voucher_no="JV-OFF-1",
            voucher_type="JOURNAL",
            voucher_date=self.fy.start_date,
            status="POSTED",
            created_by=user,
        )
        Device.objects.create(user=user, company=self.company, device_id="MOB-1", device_name="Phone")
        r_off = hr.post(f"/api/hr/staff/{staff_id}/set-status/", {"status": "TERMINATED", "reason": "Resigned"}, format="json", **headers)
        self.assertEqual(r_off.status_code, 200)
        self.assertEqual(r_off.data["revoked_devices"], 1)

        # Terminated employee blocked from password and 6-digit code login
        self.assertEqual(APIClient().post("/api/v1/auth/login/", {"identifier": user.username, "password": "NewPassword@9"}, format="json").status_code, 403)
        self.assertEqual(APIClient().post("/api/auth/staff-code/login/", {"identifier": user.username, "staff_code": "739204"}, format="json").status_code, 403)

        # Historic voucher & audit trail intact
        self.assertTrue(Voucher.objects.filter(id=v.id).exists())
        self.assertTrue(UserSecurityEvent.objects.filter(user=user, event_type="STAFF_OFFBOARDED").exists())

