import unittest
import os
import tempfile
from app import app, db, User, Wallet
from models import Contribution, Loan, Transaction

class MedlabCooperativeTestCase(unittest.TestCase):
    
    def setUp(self):
        self.db_fd, app.config['DATABASE'] = tempfile.mkstemp()
        app.config['TESTING'] = True
        app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'
        app.config['WTF_CSRF_ENABLED'] = False
        
        self.app = app.test_client()
        with app.app_context():
            db.create_all()
    
    def tearDown(self):
        os.close(self.db_fd)
        os.unlink(app.config['DATABASE'])
    
    def test_index_page(self):
        response = self.app.get('/', follow_redirects=True)
        self.assertEqual(response.status_code, 200)
        self.assertIn(b'National Medlab Cooperative', response.data)
    
    def test_user_registration(self):
        response = self.app.post('/register', data=dict(
            full_name='Test User',
            email='test@example.com',
            phone='08012345678',
            password='test123',
            confirm_password='test123'
        ), follow_redirects=True)
        
        self.assertEqual(response.status_code, 200)
        
        # Check if user was created
        with app.app_context():
            user = User.query.filter_by(email='test@example.com').first()
            self.assertIsNotNone(user)
            self.assertEqual(user.full_name, 'Test User')
            self.assertTrue(user.registration_number.startswith('NLB'))
    
    def test_registration_number_generation(self):
        with app.app_context():
            # Create first user
            user1 = User(
                full_name='User One',
                email='user1@example.com',
                phone='08012345678',
                password_hash='hash1',
                registration_number='NLB000001'
            )
            db.session.add(user1)
            db.session.commit()
            
            # Test registration number generation
            from app import generate_registration_number
            reg_num = generate_registration_number()
            self.assertEqual(reg_num, 'NLB000002')
    
    def test_login_blocks_unverified_user(self):
        # Create unverified user
        with app.app_context():
            user = User(
                full_name='Test User',
                email='test@example.com',
                phone='08012345678',
                password_hash='hash',
                registration_number='NLB000001',
                is_verified=False
            )
            db.session.add(user)
            db.session.commit()
        
        # Try to login
        response = self.app.post('/login', data=dict(
            email='test@example.com',
            password='test123'
        ), follow_redirects=True)
        
        self.assertIn(b'verify your email', response.data)
    
    def test_wallet_creation(self):
        with app.app_context():
            # Create user
            user = User(
                full_name='Test User',
                email='test@example.com',
                phone='08012345678',
                password_hash='hash',
                registration_number='NLB000001',
                is_verified=True
            )
            db.session.add(user)
            db.session.commit()
            
            # Check if wallet was created
            wallet = Wallet.query.filter_by(user_id=user.id).first()
            self.assertIsNotNone(wallet)
            self.assertEqual(wallet.balance, 0.0)
    
    def test_contribution_creation(self):
        with app.app_context():
            # Create user and wallet
            user = User(
                full_name='Test User',
                email='test@example.com',
                phone='08012345678',
                password_hash='hash',
                registration_number='NLB000001',
                is_verified=True
            )
            db.session.add(user)
            db.session.commit()
            
            # Create contribution
            contribution = Contribution(
                user_id=user.id,
                amount=5000.0,
                payment_method='manual',
                status='pending'
            )
            db.session.add(contribution)
            db.session.commit()
            
            # Check contribution
            saved_contribution = Contribution.query.filter_by(user_id=user.id).first()
            self.assertIsNotNone(saved_contribution)
            self.assertEqual(saved_contribution.amount, 5000.0)

if __name__ == '__main__':
    unittest.main()
