# Registration API Tests for Opel Lifts Attendance Management System
# Testing: POST /api/auth/register endpoint

import pytest
import requests
import os

BASE_URL = os.environ['EXPO_PUBLIC_BACKEND_URL'].rstrip('/')

class TestRegistration:
    """Registration endpoint tests"""
    
    def test_register_valid_data_success(self, api_client):
        """Test POST /api/auth/register with valid data returns success"""
        # Cleanup if test user exists from previous run
        test_emp_id = "TEST_REG001"
        
        # Delete if exists
        try:
            login_resp = api_client.post(
                f"{BASE_URL}/api/auth/login",
                json={"employee_id": "ADMIN001", "password": "admin123"}
            )
            if login_resp.status_code == 200:
                admin_token = login_resp.json()["token"]
                api_client.delete(
                    f"{BASE_URL}/api/admin/employees/{test_emp_id}",
                    headers={"Authorization": f"Bearer {admin_token}"}
                )
        except:
            pass
        
        # Register new employee with unique data
        import time
        unique_suffix = str(int(time.time()))[-6:]
        response = api_client.post(
            f"{BASE_URL}/api/auth/register",
            json={
                "name": "Test Registration User",
                "email": f"testreg{unique_suffix}@opellifts.com",
                "mobile": f"98765{unique_suffix}",
                "employee_id": test_emp_id,
                "password": "test1234"
            }
        )
        
        assert response.status_code == 200, f"Expected 200, got {response.status_code}: {response.text}"
        data = response.json()
        assert "message" in data
        assert "employee_id" in data
        assert data["employee_id"] == test_emp_id
        assert "Registration successful" in data["message"]
        print(f"✓ Registration successful: {data['employee_id']}")
        
        # Verify user exists by logging in
        login_response = api_client.post(
            f"{BASE_URL}/api/auth/login",
            json={"employee_id": test_emp_id, "password": "test1234"}
        )
        assert login_response.status_code == 200, "Newly registered user cannot login"
        login_data = login_response.json()
        assert login_data["employee"]["employee_id"] == test_emp_id
        assert login_data["employee"]["name"] == "Test Registration User"
        assert login_data["employee"]["role"] == "employee"
        print(f"✓ Newly registered user can login: {login_data['employee']['name']}")
    
    def test_register_duplicate_employee_id(self, api_client):
        """Test POST /api/auth/register rejects duplicate employee_id"""
        # Use existing employee ID (ADMIN001 is seeded)
        response = api_client.post(
            f"{BASE_URL}/api/auth/register",
            json={
                "name": "Duplicate Test",
                "email": "duplicate@opellifts.com",
                "mobile": "9999888877",
                "employee_id": "ADMIN001",  # Already exists
                "password": "test1234"
            }
        )
        
        assert response.status_code == 400, f"Expected 400, got {response.status_code}"
        data = response.json()
        assert "detail" in data
        assert "Employee ID already exists" in data["detail"]
        print(f"✓ Duplicate employee_id rejected: {data['detail']}")
    
    def test_register_duplicate_email(self, api_client):
        """Test POST /api/auth/register rejects duplicate email"""
        # Use existing email from EMP099 who was manually registered
        response = api_client.post(
            f"{BASE_URL}/api/auth/register",
            json={
                "name": "Duplicate Email Test",
                "email": "test@opellifts.com",  # EMP099's email
                "mobile": "8888777766",
                "employee_id": "TEST_REG_DUPEMAIL2",
                "password": "test1234"
            }
        )
        
        assert response.status_code == 400, f"Expected 400, got {response.status_code}"
        data = response.json()
        assert "detail" in data
        assert "Email already registered" in data["detail"]
        print(f"✓ Duplicate email rejected: {data['detail']}")
    
    def test_register_duplicate_mobile(self, api_client):
        """Test POST /api/auth/register rejects duplicate mobile"""
        # Use existing mobile from EMP099 who was manually registered
        response = api_client.post(
            f"{BASE_URL}/api/auth/register",
            json={
                "name": "Duplicate Mobile Test",
                "email": "dupmobile2@opellifts.com",
                "mobile": "9876543299",  # EMP099's mobile
                "employee_id": "TEST_REG_DUPMOBILE2",
                "password": "test1234"
            }
        )
        
        assert response.status_code == 400, f"Expected 400, got {response.status_code}"
        data = response.json()
        assert "detail" in data
        assert "Mobile number already registered" in data["detail"]
        print(f"✓ Duplicate mobile rejected: {data['detail']}")
    
    def test_register_short_password(self, api_client):
        """Test POST /api/auth/register rejects password <6 characters"""
        response = api_client.post(
            f"{BASE_URL}/api/auth/register",
            json={
                "name": "Short Password Test",
                "email": "shortpass@opellifts.com",
                "mobile": "7777666655",
                "employee_id": "TEST_REG_SHORTPW",
                "password": "12345"  # Only 5 characters
            }
        )
        
        assert response.status_code == 400, f"Expected 400, got {response.status_code}"
        data = response.json()
        assert "detail" in data
        assert "at least 6 characters" in data["detail"]
        print(f"✓ Short password rejected: {data['detail']}")
    
    def test_register_invalid_email(self, api_client):
        """Test POST /api/auth/register rejects invalid email"""
        response = api_client.post(
            f"{BASE_URL}/api/auth/register",
            json={
                "name": "Invalid Email Test",
                "email": "notanemail",  # No @ symbol
                "mobile": "6666555544",
                "employee_id": "TEST_REG_INVALIDEMAIL",
                "password": "test1234"
            }
        )
        
        assert response.status_code == 400, f"Expected 400, got {response.status_code}"
        data = response.json()
        assert "detail" in data
        assert "Valid email is required" in data["detail"]
        print(f"✓ Invalid email rejected: {data['detail']}")
    
    def test_register_missing_name(self, api_client):
        """Test POST /api/auth/register rejects empty name"""
        response = api_client.post(
            f"{BASE_URL}/api/auth/register",
            json={
                "name": "   ",  # Whitespace only
                "email": "noname@opellifts.com",
                "mobile": "5555444433",
                "employee_id": "TEST_REG_NONAME",
                "password": "test1234"
            }
        )
        
        assert response.status_code == 400, f"Expected 400, got {response.status_code}"
        data = response.json()
        assert "detail" in data
        assert "Name is required" in data["detail"]
        print(f"✓ Empty name rejected: {data['detail']}")
    
    def test_register_invalid_mobile(self, api_client):
        """Test POST /api/auth/register rejects mobile <10 digits"""
        response = api_client.post(
            f"{BASE_URL}/api/auth/register",
            json={
                "name": "Invalid Mobile Test",
                "email": "invalidmob@opellifts.com",
                "mobile": "123",  # Less than 10 digits
                "employee_id": "TEST_REG_INVALIDMOB",
                "password": "test1234"
            }
        )
        
        assert response.status_code == 400, f"Expected 400, got {response.status_code}"
        data = response.json()
        assert "detail" in data
        assert "Valid mobile number is required" in data["detail"]
        print(f"✓ Invalid mobile rejected: {data['detail']}")
