"""Tests for auth endpoints."""

import sys, os
sys.path.insert(0, os.path.dirname(__file__))

import pytest
import pytest_asyncio
from httpx import AsyncClient
from helpers import auth_header, register_and_login


@pytest.mark.asyncio
async def test_register(client: AsyncClient):
    resp = await client.post(
        "/api/auth/register",
        json={"username": "newuser", "password": "password123"},
    )
    assert resp.status_code == 201
    data = resp.json()
    assert "token" in data
    assert "user_id" in data


@pytest.mark.asyncio
async def test_register_duplicate(client: AsyncClient):
    await client.post(
        "/api/auth/register",
        json={"username": "dupuser", "password": "password123"},
    )
    resp = await client.post(
        "/api/auth/register",
        json={"username": "dupuser", "password": "password123"},
    )
    assert resp.status_code == 409


@pytest.mark.asyncio
async def test_login(client: AsyncClient):
    await client.post(
        "/api/auth/register",
        json={"username": "loginuser", "password": "mypassword"},
    )
    resp = await client.post(
        "/api/auth/login",
        json={"username": "loginuser", "password": "mypassword"},
    )
    assert resp.status_code == 200
    data = resp.json()
    assert "token" in data
    assert "user_id" in data


@pytest.mark.asyncio
async def test_login_wrong_password(client: AsyncClient):
    await client.post(
        "/api/auth/register",
        json={"username": "wrongpw", "password": "correct"},
    )
    resp = await client.post(
        "/api/auth/login",
        json={"username": "wrongpw", "password": "incorrect"},
    )
    assert resp.status_code == 401


@pytest.mark.asyncio
async def test_refresh(client: AsyncClient):
    token, user_id = await register_and_login(client)
    resp = await client.post(
        "/api/auth/refresh",
        headers=auth_header(token),
    )
    assert resp.status_code == 200
    data = resp.json()
    assert "token" in data
    assert data["user_id"] == user_id


@pytest.mark.asyncio
async def test_refresh_no_token(client: AsyncClient):
    resp = await client.post("/api/auth/refresh")
    assert resp.status_code in (401, 403)
