"""Email + password login, lockout, change-password, sessions (DB-backed)."""
import pytest

from app.core import error_codes as errors
from conftest import login, login_as
from testkit import API, advance, one, q

ACTORS = {
    "dc_staff": "DC_STAFF", "dc_manager": "DC_MANAGER", "outlet_staff": "OUTLET_STAFF",
    "outlet_manager": "OUTLET_MANAGER", "head_office": "HEAD_OFFICE",
}


async def post_login(client, email, password):
    return await client.post(f"{API}/auth/login", json={"email": email, "password": password})


# ------------------------------------------------------------------ login
async def test_every_seeded_actor_has_a_makeshift_email_and_the_default_password(client):
    for name, role in ACTORS.items():
        r = await post_login(client, f"{name}@neuro.local", "123456")
        assert r.status_code == 200, (name, r.text)
        body = r.json()
        assert body["role"] == role and body["email"] == f"{name}@neuro.local"
        assert body["name"] == name and body["must_change_password"] is True
        assert body["token_type"] == "bearer" and body["expires_in_seconds"] == 12 * 3600
        assert (body["site_id"] is None) == (role == "HEAD_OFFICE")
    dhn = (await post_login(client, "outlet_manager@neuro.local", "123456")).json()
    assert dhn["site_code"] == "OUT-DHN"
    assert (await post_login(client, "head_office@neuro.local", "123456")).json()["site_code"] is None


async def test_the_email_is_case_and_space_insensitive(client):
    assert (await post_login(client, "  DC_Staff@NEURO.local ", "123456")).status_code == 200


async def test_wrong_credentials_all_look_the_same(client):
    unknown = await post_login(client, "nobody@neuro.local", "123456")
    wrong = await post_login(client, "dc_staff@neuro.local", "not-it")
    for r in (unknown, wrong):
        assert r.status_code == 401 and r.json()["error"] == errors.UNAUTHENTICATED
    assert unknown.json()["detail"] == wrong.json()["detail"] == "Invalid email or password"


@pytest.mark.parametrize("body", [{}, {"email": "dc_staff@neuro.local"}, {"password": "x"},
                                  {"email": "not-an-email", "password": "x"},
                                  {"email": "dc_staff@neuro.local", "password": ""},
                                  {"username": "dc_staff"}])
async def test_a_bad_login_body_is_a_validation_error(client, body):
    r = await client.post(f"{API}/auth/login", json=body)
    assert r.status_code == 422 and r.json()["error"] == errors.VALIDATION_FAILED


async def test_me_restores_the_session(client):
    h = await login(client, "outlet_manager")
    me = (await client.get(f"{API}/auth/me", headers=h)).json()
    assert me["email"] == "outlet_manager@neuro.local" and me["role"] == "OUTLET_MANAGER"
    assert me["site_code"] == "OUT-DHN" and me["must_change_password"] is True
    assert (await client.get(f"{API}/auth/me")).status_code == 401


async def test_passwords_are_stored_hashed_and_salted(client, db):
    rows = await q(db, "SELECT password_hash FROM app_user")
    hashes = [r[0] for r in rows]
    assert len(set(hashes)) == len(hashes) == 5  # same password, different salts
    assert all(h.startswith("pbkdf2_sha256$") and "123456" not in h for h in hashes)


# ------------------------------------------------------------------ lockout
async def test_five_wrong_passwords_lock_the_account_for_fifteen_minutes(client, db):
    for _ in range(5):
        assert (await post_login(client, "dc_staff@neuro.local", "bad")).status_code == 401
    locked = await post_login(client, "dc_staff@neuro.local", "123456")  # even the right one
    assert locked.status_code == 401 and "Too many wrong passwords" in locked.json()["detail"]
    assert "Dhaka" in locked.json()["detail"]
    assert await one(db, "SELECT count(*) FROM audit_log WHERE event = 'LOGIN_LOCKED'") == 1
    ho = await login(client, "head_office")
    await advance(client, 0.1)  # 6 minutes: still locked
    assert (await post_login(client, "dc_staff@neuro.local", "123456")).status_code == 401
    await advance(client, 0.2)  # 18 minutes in total: free again
    assert (await post_login(client, "dc_staff@neuro.local", "123456")).status_code == 200
    assert await one(db, "SELECT failed_attempts FROM app_user WHERE name = 'dc_staff'") == 0
    other = await post_login(client, "dc_manager@neuro.local", "123456")
    assert other.status_code == 200  # only that account was locked
    assert ho


async def test_a_good_login_resets_the_failure_count(client, db):
    for _ in range(4):
        await post_login(client, "dc_staff@neuro.local", "bad")
    assert (await post_login(client, "dc_staff@neuro.local", "123456")).status_code == 200
    for _ in range(4):
        await post_login(client, "dc_staff@neuro.local", "bad")
    assert (await post_login(client, "dc_staff@neuro.local", "123456")).status_code == 200


# ------------------------------------------------------------------ change password
async def change(client, headers, current, new):
    return await client.post(f"{API}/auth/change-password", headers=headers,
                             json={"current_password": current, "new_password": new})


async def test_changing_the_password_ends_old_sessions_and_hands_back_a_fresh_token(client, db):
    old = await login(client, "dc_staff")
    r = await change(client, old, "123456", "A-better-pass-1")
    assert r.status_code == 200, r.text
    body = r.json()
    assert body["must_change_password"] is False
    fresh = {"Authorization": f"Bearer {body['access_token']}"}
    assert (await client.get(f"{API}/auth/me", headers=fresh)).status_code == 200
    stale = await client.get(f"{API}/auth/me", headers=old)  # the old token is dead
    assert stale.status_code == 401 and "no longer valid" in stale.json()["detail"]
    assert (await post_login(client, "dc_staff@neuro.local", "123456")).status_code == 401
    assert (await post_login(client, "dc_staff@neuro.local", "A-better-pass-1")).status_code == 200
    assert (await post_login(client, "dc_staff@neuro.local", "A-better-pass-1")
            ).json()["must_change_password"] is False
    assert await one(db, "SELECT count(*) FROM audit_log WHERE event = 'PASSWORD_CHANGED'") == 1


async def test_change_password_rules(client, db):
    h = await login(client, "outlet_staff")
    wrong = await change(client, h, "not-the-current", "A-better-pass-1")
    assert wrong.status_code == 401 and wrong.json()["error"] == errors.UNAUTHENTICATED
    for new in ("short", "123456", " leading-space1", "12345678" * 17):
        r = await change(client, h, "123456", new)
        assert r.status_code == 422 and r.json()["error"] == errors.VALIDATION_FAILED, new
    same = await change(client, h, "123456", "123456")
    assert same.status_code == 422
    # none of the failures changed anything
    assert (await post_login(client, "outlet_staff@neuro.local", "123456")).status_code == 200
    assert (await client.get(f"{API}/auth/me", headers=h)).status_code == 200


async def test_guessing_the_current_password_counts_toward_the_lockout(client):
    h = await login(client, "outlet_staff")
    for _ in range(5):
        assert (await change(client, h, "guess", "A-better-pass-1")).status_code == 401
    r = await post_login(client, "outlet_staff@neuro.local", "123456")
    assert r.status_code == 401 and "Too many" in r.json()["detail"]


async def test_a_deleted_account_cannot_use_its_token(client, db):
    from sqlalchemy import text

    from testkit import user_headers

    site = await one(db, "SELECT id FROM site WHERE code = 'OUT-GUL'")
    h = await user_headers(client, db, "OUTLET_STAFF", site, email="temp@neuro.local")
    assert (await client.get(f"{API}/auth/me", headers=h)).status_code == 200
    async with db.begin() as conn:
        await conn.execute(text("DELETE FROM app_user WHERE email = 'temp@neuro.local'"))
    assert (await client.get(f"{API}/auth/me", headers=h)).status_code == 401


async def test_login_as_helper_matches_the_endpoint(client):
    h = await login_as(client, "head_office@neuro.local", "123456")
    assert (await client.get(f"{API}/auth/me", headers=h)).json()["role"] == "HEAD_OFFICE"
