import os
import pytest
from fastapi.testclient import TestClient
from app.models.user import DB_PATH, init_db
from app.core.auth import seed_admin

# Clean DB file before test session
if os.path.exists(DB_PATH):
    try:
        os.remove(DB_PATH)
    except Exception:
        pass

init_db()
seed_admin()

from app.main import app
client = TestClient(app)

def test_admin_seed_and_login():
    # 1. Login with default admin password
    res = client.post("/api/v1/auth/login", json={
        "username": "admin",
        "password": "admin123"
    })
    assert res.status_code == 200, res.text
    data = res.json()
    assert "access_token" in data
    assert data["user"]["role"] == "admin"
    assert data["user"]["must_change_password"] is True
    
    token = data["access_token"]
    headers = {"Authorization": f"Bearer {token}"}
    
    # 2. Change password
    res = client.post("/api/v1/auth/change-password", headers=headers, json={
        "old_password": "admin123",
        "new_password": "admin_new_password_2026"
    })
    assert res.status_code == 200, res.text
    
    # 3. Login with new password
    res = client.post("/api/v1/auth/login", json={
        "username": "admin",
        "password": "admin_new_password_2026"
    })
    assert res.status_code == 200, res.text
    assert res.json()["user"]["must_change_password"] is False

def test_user_registration_and_quota():
    # 1. Register new user
    res = client.post("/api/v1/auth/register", json={
        "username": "testuser_studio",
        "email": "testuser@studio.com",
        "password": "userpass123"
    })
    assert res.status_code == 200, res.text
    token = res.json()["access_token"]
    headers = {"Authorization": f"Bearer {token}"}
    
    # 2. Check profile
    res = client.get("/api/v1/auth/profile", headers=headers)
    assert res.status_code == 200, res.text
    prof = res.json()
    assert prof["username"] == "testuser_studio"
    assert prof["quota"]["storage_limit_mb"] == 500
    
    # 3. Temp Project Auto-save
    res = client.post("/api/v1/projects/temp", json={"data_json": '{"tracks": []}'})
    assert res.status_code == 200, res.text
