from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timezone
import os
from pathlib import Path
import tempfile
import unittest
from unittest.mock import patch

from cryptography.fernet import Fernet
from fastapi.testclient import TestClient

from arpay.cli import DEMO_ADMIN, DEMO_CUSTOMER, seed_demo
from arpay.main import create_app
from arpay.security import generate_totp, now
from arpay.finance import Purchase, apply_purchase

ORIGIN = "http://127.0.0.1:8000"


class ArPayIntegration(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.temporary = tempfile.TemporaryDirectory()
        mysql = os.getenv("ARPAY_TEST_MYSQL_URL")
        values = {"ARPAY_ORIGIN": ORIGIN, "ARPAY_ENV": "development", "ARPAY_DEMO": "1",
                  "ARPAY_DATABASE_URL": mysql or f"sqlite:///{Path(cls.temporary.name) / 'test.sqlite'}",
                  "ARPAY_ENCRYPTION_KEY": Fernet.generate_key().decode()}
        cls.env = patch.dict(os.environ, values)
        cls.env.start()
        cls.app = create_app()
        cls.db = cls.app.state.db
        if not mysql:
            cls.db.init_sqlite()
        seed_demo(cls.db)
        cls.customer, cls.customer_recovery, cls.secret = cls.login("customer", DEMO_CUSTOMER)
        cls.admin, _, _ = cls.login("admin", DEMO_ADMIN)
        with cls.db.transaction() as db:
            row = db.one("SELECT id FROM users WHERE email='other@arpay.example'")
            cls.other_id = row["id"]
            cls.other_card = db.one("SELECT id FROM cards WHERE user_id=?", (cls.other_id,))["id"]
        cls.customer_id = cls.customer.get("/api/v1/auth/session").json()["id"]
        cls.card = cls.customer.get("/api/v1/customer/cards").json()[0]["id"]

    @classmethod
    def tearDownClass(cls):
        cls.admin.close()
        cls.customer.close()
        cls.env.stop()
        cls.temporary.cleanup()

    @classmethod
    def new_browser(cls):
        return TestClient(cls.app, base_url=ORIGIN, headers={"Origin": ORIGIN})

    @classmethod
    def write(cls, client, path, data=None, method="POST"):
        state = client.get("/api/v1/auth/session").json()
        return client.request(method, "/api/v1" + path, json=data, headers={"X-CSRF-Token": state["csrf"]})

    @classmethod
    def login(cls, portal, password):
        client = cls.new_browser()
        r = client.post("/api/v1/auth/login", json={"email": f"{portal}@arpay.example", "password": password, "portal": portal})
        assert r.status_code == 200, r.text
        assert r.json()["stage"] == "setup"
        assert client.get("/api/v1/" + portal + "/summary").status_code == 403
        setup = cls.write(client, "/auth/totp/setup").json()
        assert "<svg" in setup["qr"]
        secret = setup["manual_key"]
        response = cls.write(client, "/auth/totp/verify", {"code": generate_totp(secret, now() // 30)})
        assert response.status_code == 200, response.text
        assert client.get("/api/v1/" + portal + "/summary").status_code == 200
        return client, response.json()["recovery_codes"], secret

    def expect(self, response, status=200):
        self.assertEqual(response.status_code, status, response.text)
        return response.json()

    def current_balance(self, card_id=None):
        return self.expect(self.customer.get(f"/api/v1/customer/cards/{card_id or self.card}"))["available"]

    def test_01_security_boundaries_and_dynamic_routes(self):
        self.assertEqual(self.customer.get("/").status_code, 200)
        self.assertEqual(self.customer.get("/admin").status_code, 200)
        self.assertEqual(self.customer.get("/manifest.webmanifest").status_code, 200)
        self.assertEqual(self.customer.get("/api/v1/admin/summary").status_code, 401)
        self.assertEqual(self.admin.get("/api/v1/customer/summary").status_code, 401)
        self.assertEqual(self.customer.get(f"/api/v1/customer/cards/{self.other_card}").status_code, 404)
        self.expect(self.write(self.customer, f"/customer/cards/{self.other_card}/freeze", {"frozen":True}, "PATCH"), 404)
        self.expect(self.write(self.customer, "/customer/funding", {"card_id":self.other_card,"amount":100}), 404)
        self.assertEqual(self.customer.post("/api/v1/customer/notifications/read").status_code, 403)
        csrf = self.customer.get("/api/v1/auth/session").json()["csrf"]
        wrong_origin = self.customer.post("/api/v1/customer/notifications/read",
                                         headers={"Origin":"https://other.example","X-CSRF-Token":csrf})
        self.assertEqual(wrong_origin.status_code, 403)
        self.assertEqual(self.current_balance(), 24700)
        self.assertEqual(self.customer.get("/").headers["x-frame-options"], "DENY")

    def test_02_exactly_once_funding_and_immutable_ledger(self):
        before = self.current_balance()
        fund = self.expect(self.write(self.customer, "/customer/funding", {"card_id":self.card,"amount":10000}), 201)
        path = "/admin/funding/" + fund["id"]
        for intermediate in ["PROCESSING", "WAITING"]:
            self.expect(self.write(self.admin, path, {"status":intermediate}, "PATCH"))
            self.assertEqual(self.current_balance(), before)

        session_cookies = dict(self.admin.cookies)
        def complete(_):
            with self.new_browser() as parallel_admin:
                parallel_admin.cookies.update(session_cookies)
                return self.write(parallel_admin,path,{"status":"COMPLETED","payment_reference":"test-multi-confirm"},"PATCH")
        with ThreadPoolExecutor(max_workers=6) as executor:
            results = list(executor.map(complete, range(6)))
        for result in results:
            self.expect(result)
        self.assertEqual(self.current_balance(), before + 10000)
        with self.db.transaction() as db:
            row = db.one("SELECT ledger_id FROM funding_payments WHERE funding_id=?", (fund["id"],))
            self.assertIsNotNone(row["ledger_id"])
        with self.assertRaises(Exception), self.db.transaction(write=True) as db:
            db.change("UPDATE balance_ledger SET amount=0 WHERE id=?", (row["ledger_id"],))
        with self.assertRaises(Exception), self.db.transaction(write=True) as db:
            db.change("DELETE FROM balance_ledger WHERE id=?", (row["ledger_id"],))
        self.expect(self.write(self.admin, path, {"status":"REJECTED"}, "PATCH"), 409)

    def test_03_fees_freeze_limits_refund_policy_and_history(self):
        before = self.current_balance()
        data = {"card_id":self.card,"reference":"test-accepted","merchant":"Coffee Review","amount":3000,"channel":"ONLINE"}
        self.expect(self.write(self.customer, f"/customer/cards/{self.card}/freeze", {"frozen":True}, "PATCH"))
        decline = self.expect(self.write(self.admin, "/admin/test/purchases", data | {"reference":"frozen"}))
        self.assertEqual(decline["status"], "FAILED")
        self.assertEqual(self.current_balance(), before)
        self.expect(self.write(self.customer, f"/customer/cards/{self.card}/freeze", {"frozen":False}, "PATCH"))
        limits = {"daily_limit":None,"monthly_limit":None,"online_limit":None,"merchant_limit":3000}
        self.expect(self.write(self.customer, f"/customer/cards/{self.card}/limits",limits,"PATCH"),403)
        self.expect(self.write(self.admin, f"/admin/cards/{self.card}/limits", limits, "PATCH"))
        capped = self.expect(self.write(self.admin, "/admin/test/purchases", data | {"reference":"limit"}))
        self.assertEqual(capped["status"], "FAILED")
        self.expect(self.write(self.admin, f"/admin/cards/{self.card}/limits", limits | {"merchant_limit":None}, "PATCH"))
        one = self.expect(self.write(self.admin, "/admin/test/purchases", data))
        two = self.expect(self.write(self.admin, "/admin/test/purchases", data))
        self.assertEqual(one["id"], two["id"])
        self.assertEqual(one["fee"], 60)
        self.assertEqual(one["balance_after"], before - 3060)
        self.assertEqual(self.current_balance(), before - 3060)
        detail = self.expect(self.customer.get("/api/v1/customer/transactions/" + one["id"]))
        self.assertEqual(detail["mode"], "TEST")
        for _ in range(2):
            self.expect(self.write(self.admin, "/admin/test/purchases/" + one["id"] + "/return", {"status":"REFUNDED"}),409)
        self.assertEqual(self.current_balance(), before-3060)
        with self.db.transaction(write=True) as db:
            another = apply_purchase(db, Purchase("test-isolation",self.other_card,"Test","",100,"ONLINE","TEST"))
        self.assertEqual(self.customer.get("/api/v1/customer/transactions/" + another["id"]).status_code, 404)
        self.assertEqual(len(self.expect(self.customer.get("/api/v1/customer/activity"))["days"]), 7)

    def test_04_customers_orders_features_notifications_and_support(self):
        new = self.expect(self.write(self.admin,"/admin/customers",{"email":"audit-case@arpay.example","full_name":"Audit Test"}), 201)
        self.assertGreaterEqual(len(new["temporary_password"]), 12)
        card = self.expect(self.write(self.admin,"/admin/cards",{"user_id":self.customer_id,"network":"MASTERCARD",
                                                               "first4":"5321","last4":"2580","initial_balance":2500}), 201)
        order = self.expect(self.write(self.customer,"/customer/orders",{"network":"MASTERCARD","card_type":"VIRTUAL",
                                                                       "fee_quote":1000,"terms_accepted":True}), 201)
        path = "/admin/orders/" + order["id"]
        self.expect(self.write(self.admin,path,{"status":"PROCESSING"},"PATCH"))
        self.expect(self.write(self.admin,path,{"status":"ISSUED","card_id":self.other_card},"PATCH"), 404)
        for _ in range(2):
            self.expect(self.write(self.admin,path,{"status":"ISSUED","card_id":card["id"]},"PATCH"))
        self.assertEqual(self.current_balance(card["id"]), 1500)
        self.expect(self.write(self.admin,"/admin/features/crypto",{"enabled":True},"PUT"))
        settings = self.expect(self.admin.get("/api/v1/admin/features"))
        self.assertTrue(next(f for f in settings if f["name"] == "crypto")["enabled"])
        overview = self.expect(self.customer.get("/api/v1/customer/summary"))
        self.assertTrue(all(not f["available"] for f in overview["features"]))
        notices = self.expect(self.customer.get("/api/v1/customer/notifications"))
        self.assertTrue(any(row["title"] == "Card order issued" for row in notices))
        self.expect(self.write(self.customer,"/customer/notifications/read"))
        self.assertTrue(all(row["read_at"] for row in self.expect(self.customer.get("/api/v1/customer/notifications"))))
        ticket = self.expect(self.write(self.customer,"/customer/support",{"subject":"Order review","message":"Please review the record."}), 201)
        self.expect(self.write(self.admin,"/admin/support/" + ticket["id"],{"reply":"Reviewed."},"PATCH"))
        self.assertEqual(self.expect(self.customer.get("/api/v1/customer/support"))[0]["reply"], "Reviewed.")
        self.assertTrue(any(x["action"] == "ORDER_ISSUED" for x in self.expect(self.admin.get("/api/v1/admin/audit"))))

    def test_05_recovery_code_is_single_use_and_revocation_works(self):
        alternate = self.new_browser()
        credentials = {"email":"customer@arpay.example","password":DEMO_CUSTOMER,"portal":"customer"}
        self.expect(alternate.post("/api/v1/auth/login",json=credentials))
        self.expect(self.write(alternate,"/auth/totp/verify",{"code":self.customer_recovery[0]}))
        self.assertEqual(alternate.get("/api/v1/customer/summary").status_code, 200)
        devices = self.expect(self.customer.get("/api/v1/auth/sessions"))
        alternative = next(x for x in devices["sessions"] if x["id"] != devices["current"])
        self.expect(self.write(self.customer,"/auth/sessions/" + alternative["id"],method="DELETE"))
        self.assertEqual(alternate.get("/api/v1/customer/summary").status_code, 401)
        self.expect(alternate.post("/api/v1/auth/login",json=credentials))
        self.expect(self.write(alternate,"/auth/totp/verify",{"code":self.customer_recovery[0]}), 401)
        alternate.close()


    def test_06_holder_names_and_history_are_independent_per_card(self):
        names = ["MD RABBI", "RABBI HOSSAIN", "PRILEXO", "Travel", "Office"]
        holders = {}
        for index, name in enumerate(names):
            fields = {"user_id": self.customer_id, "card_holder_name": name, "nickname": f"Card {index}",
                      "network": "VISA" if index % 2 == 0 else "MASTERCARD",
                      "first4": "0432", "last4": f"000{index}", "initial_balance": 5000 + index,
                      "expiry_month": index + 1, "expiry_year": 2030, "status": "ACTIVE",
                      "admin_note": "Keep private", "order_reference": "Internal batch"}
            card = self.expect(self.write(self.admin, "/admin/cards", fields), 201)
            holders[card["id"]] = fields

        renamed = next(iter(holders))
        self.expect(self.write(self.admin, f"/admin/cards/{renamed}", {"card_holder_name": "MD RABBI H."}, "PATCH"))
        holders[renamed]["card_holder_name"] = "MD RABBI H."
        self.expect(self.write(self.customer, f"/admin/cards/{renamed}", {"card_holder_name": "Cannot edit"}, "PATCH"), 401)
        self.expect(self.write(self.customer, f"/customer/cards/{renamed}/freeze",
                               {"frozen": True, "card_holder_name": "Cannot edit"}, "PATCH"), 422)
        self.expect(self.write(self.admin, f"/admin/cards/{renamed}", {"card_holder_name": "  "}, "PATCH"), 422)
        self.expect(self.write(self.admin, f"/admin/cards/{renamed}", {"expiry_year": None}, "PATCH"), 422)
        profile = self.expect(self.customer.get("/api/v1/customer/profile"))
        self.expect(self.write(self.customer, "/customer/profile", {"full_name": "Changed profile"}, "PATCH"))
        try:
            visible = self.expect(self.customer.get("/api/v1/customer/cards"))
            visible = [card for card in visible if card["id"] in holders]
            self.assertEqual(len(visible), 5)
            self.assertEqual(len({card["card_holder_name"] for card in visible}), 5)
            for card in visible:
                wanted = holders[card["id"]]
                self.assertEqual(card["card_holder_name"], wanted["card_holder_name"])
                self.assertEqual(card["available"], wanted["initial_balance"])
                self.assertEqual(card["expiry_month"], wanted["expiry_month"])
                self.assertEqual(card["network"], wanted["network"])
                self.assertEqual(card["masked"], "0432 •••• •••• " + wanted["last4"])
                self.assertTrue({"admin_note", "order_reference", "provider_ref"}.isdisjoint(card))

                tx = {"reference": "holder/" + wanted["last4"], "merchant": "Per-card activity",
                      "amount": 133, "fee": 12, "status": "COMPLETED", "admin_note": "Internal review",
                      "occurred_at": datetime.now(timezone.utc).isoformat()}
                created = self.expect(self.write(self.admin, f"/admin/cards/{card['id']}/transactions", tx), 201)
                history = self.expect(self.customer.get("/api/v1/customer/transactions", params={"card_id": card["id"]}))
                self.assertEqual([item["id"] for item in history], [created["id"]])
                self.assertTrue({"admin_note", "provider_ref"}.isdisjoint(history[0]))
                self.assertEqual(self.current_balance(card["id"]), wanted["initial_balance"] - 145)
            blocked = self.expect(self.write(self.admin, f"/admin/cards/{renamed}", {"status": "BLOCKED"}, "PATCH"))
            self.assertEqual(blocked["status"], "BLOCKED")
            self.expect(self.write(self.customer, f"/customer/cards/{renamed}/freeze", {"frozen": False}, "PATCH"), 409)
            self.expect(self.customer.get("/api/v1/customer/transactions", params={"card_id": self.other_card}), 404)
        finally:
            self.expect(self.write(self.customer, "/customer/profile", {"full_name": profile["full_name"]}, "PATCH"))

    def test_07_manual_posting_and_refund_policy(self):
        card = self.expect(self.write(self.admin, "/admin/cards", {
            "user_id": self.customer_id, "network": "VISA", "first4": "4111", "last4": "0022",
            "card_holder_name": "Operations Test", "provider_ref": "legacy-external-ref",
        }), 201)["id"]
        path = f"/admin/cards/{card}"
        load = {"reference": "provider/load #1", "amount": 40000, "note": "Bank transfer"}
        for _ in range(2):
            result = self.expect(self.write(self.admin, path + "/load", load), 201)
            self.assertEqual((result["balance_before"], result["balance_after"]), (0, 40000))
        self.expect(self.write(self.admin, path + "/load", load | {"amount": 1}), 409)

        fields = {"reference": "provider/transaction #1", "merchant": "Manual test", "amount": 5000, "fee": 100,
                  "occurred_at": datetime.now(timezone.utc).isoformat(), "status": "PENDING"}
        transaction = self.expect(self.write(self.admin, path + "/transactions", fields), 201)["id"]
        change = f"/admin/transactions/{transaction}/status"
        self.assertEqual(self.current_balance(card), 40000)
        self.expect(self.write(self.customer, f"/customer/cards/{card}/freeze", {"frozen": True}, "PATCH"))
        self.expect(self.write(self.admin, change, {"status": "PROCESSING"}, "PATCH"),409)
        self.expect(self.write(self.admin, change, {"status": "COMPLETED"}, "PATCH"), 409)
        self.assertEqual(self.current_balance(card), 40000)
        self.expect(self.write(self.customer, f"/customer/cards/{card}/freeze", {"frozen": False}, "PATCH"))
        for _ in range(2):
            self.expect(self.write(self.admin, change, {"status": "COMPLETED"}, "PATCH"))
        self.assertEqual(self.current_balance(card), 34900)
        self.assertEqual(self.expect(self.write(self.admin, path + "/transactions", fields), 201)["id"], transaction)
        for _ in range(2):
            self.expect(self.write(self.admin, change, {"status": "REVERSED"}, "PATCH"),409)
        ledger = self.expect(self.admin.get("/api/v1/admin/ledger", params={"card_id": card}))
        self.assertEqual(len(ledger), 3)
        self.assertEqual(self.current_balance(card), 34900)
        self.assertTrue(all(row["balance_after"] - row["balance_before"] == row["amount"] for row in ledger))
        self.assertTrue(any(row["note"] == "Bank transfer" for row in ledger))

        order = self.expect(self.write(self.customer,"/customer/orders",{
            "network":"VISA","card_type":"VIRTUAL","fee_quote":1000,"terms_accepted":True,
        }), 201)["id"]
        order_path = f"/admin/orders/{order}"
        for status in ("PROCESSING", "APPROVED"):
            self.expect(self.write(self.admin, order_path, {"status": status}, "PATCH"))
        for _ in range(2):
            self.expect(self.write(self.admin, order_path, {"status": "COMPLETED", "card_id": card}, "PATCH"))
        self.assertEqual(self.current_balance(card), 33900)

    @patch("arpay.mail.enabled", return_value=True)
    @patch("arpay.mail.send_account_link")
    def test_08_email_registration_and_single_use_password_reset(self, send_mail, enabled):
        with self.new_browser() as guest:
            email = "signed-up@arpay.example"
            self.expect(guest.post("/api/v1/auth/register", json={"email": email}), 202)
            token = send_mail.call_args.args[3]
            password = "User-selected-passphrase!"
            self.expect(guest.post("/api/v1/auth/register/confirm", json={
                "token": token, "password": password, "full_name": "New customer",
            }), 201)
            self.expect(guest.post("/api/v1/auth/login", json={
                "email": email, "password": password, "portal": "customer",
            }))
            self.expect(guest.post("/api/v1/auth/password/forgot", json={"email": email}), 202)
            reset = send_mail.call_args.args[3]
            request = {"token": reset, "password": "New-selected-passphrase!"}
            self.expect(guest.post("/api/v1/auth/password/reset", json=request))
            self.expect(guest.get("/api/v1/auth/session"), 401)
            self.expect(guest.post("/api/v1/auth/password/reset", json=request), 400)
            self.expect(guest.post("/api/v1/auth/login", json={
                "email": email, "password": request["password"], "portal": "customer",
            }))


    def test_09_assignment_and_payment_deduplication(self):
        payload = {"user_id":self.customer_id,"card_holder_name":"Card assignment","nickname":"Payment control",
                   "network":"VISA","first4":"4200","last4":"8829","expiry_year":2031,"expiry_month":2,
                   "assignment_reference":"test-assign/card-82","initial_balance":12500}
        path = "/admin/cards"
        cookies = dict(self.admin.cookies)
        def assign(_):
            with self.new_browser() as worker:
                worker.cookies.update(cookies)
                return self.expect(self.write(worker,path,payload),201)["id"]
        with ThreadPoolExecutor(max_workers=4) as executor:
            ids=list(executor.map(assign,range(4)))
        self.assertEqual(len(set(ids)),1)
        card=ids[0]
        self.assertEqual(self.current_balance(card),12500)
        self.expect(self.write(self.admin,path,payload|{"initial_balance":25000}),409)
        self.expect(self.write(self.customer,path,payload),401)
        ops=self.expect(self.admin.get("/api/v1/admin/funding"))
        opening=next(row for row in ops if row["card_id"]==card and row["status"]=="COMPLETED")
        binding="/admin/funding/" + opening["id"] + "/reference"
        for _ in range(2):
            self.expect(self.write(self.admin,binding,{"payment_reference":"opening/bank-line"},"PATCH"))
        self.expect(self.write(self.admin,f"/admin/cards/{card}/load",{
            "reference":"Opening/BANK-line","amount":12500
        }),201)
        self.assertEqual(self.current_balance(card),12500)
        for index, direct_first in enumerate((True,False)):
            reference=f"bank-statement/line-{index}"
            req=self.expect(self.write(self.admin,"/admin/funding",{"card_id":card,"amount":3500,"admin_note":"Private review"}),201)
            endpoint="/admin/funding/" + req["id"]
            self.expect(self.write(self.admin,endpoint,{"status":"COMPLETED","payment_reference":reference},"PATCH"),409)
            for stage in ("PROCESSING","WAITING"):
                self.expect(self.write(self.admin,endpoint,{"status":stage},"PATCH"))
            direct=lambda: self.expect(self.write(self.admin,f"/admin/cards/{card}/load",
                                                  {"amount":3500,"reference":reference.upper()}),201)
            approval=lambda: self.expect(self.write(self.admin,endpoint,
                                                    {"status":"COMPLETED","payment_reference":reference},"PATCH"))
            for action in ((direct, approval) if direct_first else (approval,direct)):
                action()
            self.assertEqual(self.current_balance(card),12500+3500*(index+1))
        history=self.expect(self.customer.get("/api/v1/customer/funding"))
        self.assertFalse(any("Private review" in str(row) or "admin_note" in row for row in history))
        statement=self.expect(self.customer.get("/api/v1/customer/ledger",params={"card_id":card}))
        self.assertEqual(len(statement),3)
        self.assertTrue(all("note" not in item for item in statement))

    def test_10_administrator_controls_and_expiry(self):
        data={"user_id":self.customer_id,"network":"VISA","first4":"4200","last4":"8830","card_holder_name":"Control test"}
        card=self.expect(self.write(self.admin,"/admin/cards",data),201)["id"]
        path=f"/admin/cards/{card}"
        self.expect(self.write(self.admin,path+"/load",{"amount":200,"reference":"load/control"}),201)
        self.expect(self.write(self.admin,path+"/status",{"status":"FROZEN"},"PATCH"))
        self.expect(self.write(self.customer,f"/customer/cards/{card}/freeze",{"frozen":False},"PATCH"),409)
        self.expect(self.write(self.admin,path+"/status",{"status":"ACTIVE"},"PATCH"))
        debit={"reference":"control/closed","occurred_at":datetime.now(timezone.utc).isoformat(),
               "amount":200,"fee":0,"merchant":"Control debit","status":"COMPLETED"}
        posted=self.expect(self.write(self.admin,path+"/transactions",debit),201)
        self.expect(self.write(self.admin,path,None,"DELETE"))
        self.expect(self.write(self.admin,f"/admin/transactions/{posted['id']}/status",{"status":"REVERSED"},"PATCH"),409)
        expired=self.expect(self.write(self.admin,"/admin/cards",data|{
            "last4":"8831","expiry_month":1,"expiry_year":2020
        }),201)["id"]
        info=self.expect(self.customer.get(f"/api/v1/customer/cards/{expired}"))
        self.assertEqual(info["status"],"CLOSED")
        self.assertTrue(info["expired"])
        self.expect(self.write(self.admin,f"/admin/cards/{expired}/transactions",debit|{"reference":"control/expired"}),409)
        self.expect(self.write(self.admin,f"/admin/cards/{expired}/load",{"amount":200,"reference":"load/expired"}),409)

    def test_11_optional_customer_2fa_and_two_portals_in_one_browser(self):
        contact=self.expect(self.write(self.admin,"/admin/customers",{
            "email":"portal-test@arpay.example","full_name":"Portal test"}),201)
        self.expect(self.write(self.admin,f"/admin/customers/{contact['id']}/authenticator",{"required":False},"PATCH"))
        with self.new_browser() as both:
            both.cookies.update(self.admin.cookies)
            login=both.post("/api/v1/auth/login",json={"email":"portal-test@arpay.example",
                 "password":contact["temporary_password"],"portal":"customer"},headers={"X-ArPay-Portal":"customer"})
            self.assertEqual(self.expect(login)["stage"],"password")
            csrf=self.expect(both.get("/api/v1/auth/session",headers={"X-ArPay-Portal":"customer"}))["csrf"]
            updated=both.post("/api/v1/auth/password",json={"current_password":contact["temporary_password"],
                "new_password":"Portal-new-password!"},headers={"X-ArPay-Portal":"customer","X-CSRF-Token":csrf})
            self.assertEqual(self.expect(updated)["stage"],"full")
            self.expect(both.get("/api/v1/admin/summary"))
            self.expect(both.get("/api/v1/customer/summary"))
