"""Quick test to verify delete endpoint fix"""
import sys
import os
sys.path.insert(0, os.path.dirname(__file__))

from fastapi.testclient import TestClient
from main import app
from database import get_db, Base, engine
from models.user import User, UserRole
from utils.auth import get_password_hash
from sqlalchemy.orm import Session

# Create test client
client = TestClient(app)

def setup_test_data():
    """Setup test data"""
    Base.metadata.create_all(bind=engine)
    db = next(get_db())
    
    # Create admin user if not exists
    admin = db.query(User).filter(User.email == "admin@test.com").first()
    if not admin:
        admin = User(
            email="admin@test.com",
            hashed_password=get_password_hash("admin123"),
            first_name="Admin",
            last_name="User",
            role=UserRole.ADMIN,
            is_admin=True,
            is_approved=True
        )
        db.add(admin)
        db.commit()
    
    db.close()

def get_auth_token():
    """Get authentication token"""
    response = client.post(
        "/auth/login",
        data={"username": "admin@test.com", "password": "admin123"}
    )
    if response.status_code == 200:
        return response.json()["access_token"]
    return None

def test_delete_custom_task_type():
    """Test the delete endpoint"""
    print("\n" + "="*60)
    print("Testing Custom Task Type Delete Endpoint")
    print("="*60)
    
    setup_test_data()
    token = get_auth_token()
    
    if not token:
        print("❌ Failed to get auth token")
        return
    
    headers = {"Authorization": f"Bearer {token}"}
    project_id = 1
    
    # Step 1: Add a custom task type
    print("\n1. Adding custom task type 'test_delete'...")
    add_response = client.post(
        f"/projects/{project_id}/custom-task-types",
        headers=headers,
        json={"task_type": "test_delete", "category": "asset"}
    )
    print(f"   Status: {add_response.status_code}")
    if add_response.status_code == 201:
        print("   ✓ Task type added")
        data = add_response.json()
        print(f"   Custom asset types: {data.get('custom_asset_types', [])}")
    else:
        print(f"   ✗ Failed: {add_response.text}")
        return
    
    # Step 2: Delete the custom task type
    print("\n2. Deleting custom task type 'test_delete'...")
    delete_response = client.delete(
        f"/projects/{project_id}/custom-task-types/test_delete",
        headers=headers,
        params={"category": "asset"}
    )
    print(f"   Status: {delete_response.status_code}")
    
    if delete_response.status_code == 200:
        print("   ✓ Task type deleted successfully!")
        data = delete_response.json()
        print(f"   Custom asset types: {data.get('custom_asset_types', [])}")
        
        if "test_delete" not in data.get('custom_asset_types', []):
            print("\n✅ DELETE ENDPOINT WORKING CORRECTLY!")
        else:
            print("\n⚠️  Task type still in list")
    else:
        print(f"   ✗ Failed: {delete_response.status_code}")
        print(f"   Error: {delete_response.text}")
        
        if delete_response.status_code == 405:
            print("\n❌ METHOD NOT ALLOWED ERROR - Backend needs restart!")
        
    print("\n" + "="*60)

if __name__ == "__main__":
    test_delete_custom_task_type()
