"""
Registration OTP API (PostgreSQL + mocked outbound mail).

  export INITIATIVE_DATABASE_URL="postgresql+asyncpg://initiative:initiative_secret@127.0.0.1:15432/initiatives"
  # Ensure migrations through 014_registration_otp.sql are applied.
  cd be0 && python -m unittest tests.test_registration_otp -v

Optional live login smoke (**credentials must never be committed**):

  export TEST_LIVE_AUTH_EMAIL="nltanh@ump.edu.vn"
  export TEST_LIVE_AUTH_PASSWORD='<paste password locally>'
  cd be0 && python -m unittest tests.test_registration_otp.LiveAuthLoginOptionalTests.test_login_with_env_credentials -v
"""

from __future__ import annotations

import os
import unittest
import uuid
from unittest.mock import patch

from sqlalchemy import select

from tests.auth_register_staff_fixture import register_staff_fields

_RUN_DB = os.getenv("INITIATIVE_DATABASE_URL", "").strip().lower().startswith("postgresql")

_TEST_PASSWORD = "Testpass1!"


@unittest.skipUnless(
    _RUN_DB,
    "Set INITIATIVE_DATABASE_URL=postgresql+asyncpg://.../initiatives",
)
class RegistrationOtpApiTests(unittest.IsolatedAsyncioTestCase):
    async def asyncSetUp(self) -> None:
        from src.initiative_db import engine as eng

        await eng.dispose_engine()
        await eng.init_engine()

    async def asyncTearDown(self) -> None:
        from src.initiative_db import engine as eng

        await eng.dispose_engine()

    async def _delete_user(self, email: str) -> None:
        from src.initiative_db.engine import get_session
        from src.initiative_db.models import User

        async with get_session() as session:
            user = (
                await session.execute(select(User).where(User.email == email))
            ).scalar_one_or_none()
            if user is not None:
                await session.delete(user)

    async def test_register_verify_otp_then_login(self) -> None:
        from fastapi.testclient import TestClient

        from main import app

        email = f"otp-{uuid.uuid4().hex[:12]}@ump.edu.vn"
        captured: list[str] = []

        async def grab(_to: str, raw: str) -> None:
            captured.append(raw)

        try:
            with patch.dict(os.environ, {"AUTH_MAIL_LOG_ONLY": "1"}):
                with patch("src.auth_api.deliver_registration_otp_email", side_effect=grab):
                    with TestClient(app) as client:
                        r = client.post(
                            "/api/v1/auth/register",
                            json={
                                "fullName": "OTP Tester",
                                "email": email,
                                "password": _TEST_PASSWORD,
                                "passwordConfirm": _TEST_PASSWORD,
                                **register_staff_fields(),
                            },
                        )
            self.assertEqual(r.status_code, 200, r.text)
            self.assertTrue(captured)
            otp = captured[0]
            self.assertEqual(len(otp), 6)
            self.assertTrue(otp.isdigit())

            with TestClient(app) as client:
                blocked = client.post(
                    "/api/v1/auth/login",
                    json={"email": email, "password": _TEST_PASSWORD},
                )
                self.assertEqual(blocked.status_code, 403, blocked.text)

                bad = client.post("/api/v1/auth/verify-otp", json={"email": email, "otp": "000000"})
                self.assertEqual(bad.status_code, 400, bad.text)

                ok = client.post("/api/v1/auth/verify-otp", json={"email": email, "otp": otp})
                self.assertEqual(ok.status_code, 200, ok.text)

                lg = client.post(
                    "/api/v1/auth/login",
                    json={"email": email, "password": _TEST_PASSWORD},
                )
                self.assertEqual(lg.status_code, 200, lg.text)
                self.assertTrue(lg.json().get("accessToken"))
        finally:
            await self._delete_user(email)


_LIVE_PW = os.getenv("TEST_LIVE_AUTH_PASSWORD", "").strip()
_LIVE_EMAIL = os.getenv("TEST_LIVE_AUTH_EMAIL", "nltanh@ump.edu.vn").strip().lower()


@unittest.skipUnless(
    _RUN_DB and bool(_LIVE_PW),
    "Set INITIATIVE_DATABASE_URL and TEST_LIVE_AUTH_PASSWORD for optional login smoke "
    "(use TEST_LIVE_AUTH_EMAIL to override default nltanh@ump.edu.vn).",
)
class LiveAuthLoginOptionalTests(unittest.TestCase):
    """Uses secrets from env only — passwords must never appear in source control."""

    def test_login_with_env_credentials(self) -> None:
        from fastapi.testclient import TestClient

        from main import app

        with TestClient(app) as client:
            r = client.post(
                "/api/v1/auth/login",
                json={"email": _LIVE_EMAIL, "password": _LIVE_PW},
            )
        self.assertEqual(r.status_code, 200, r.text)
        self.assertTrue(r.json().get("accessToken"))
