from app import create_app, db
from app.models import User, Project, ProjectBudget, ProjectCost, RevenueRecognition
from app.models import PurchaseRequest, PurchaseRequestItem, PurchaseOrder, PurchaseOrderItem
from app.models import Vendor, Document

app = create_app()

@app.shell_context_processor
def make_shell_context():
    return {
        'db': db, 'User': User, 'Project': Project,
        'PurchaseRequest': PurchaseRequest, 'PurchaseOrder': PurchaseOrder,
        'Vendor': Vendor, 'Document': Document
    }

@app.cli.command('init-db')
def init_db():
    """Buat tabel dan data awal (admin user)."""
    db.create_all()
    if not User.query.filter_by(username='admin').first():
        admin = User(
            username='admin',
            email='admin@perusahaan.com',
            full_name='Administrator',
            role='admin'
        )
        admin.set_password('admin123')
        db.session.add(admin)

        # Demo vendor
        vendor = Vendor(
            vendor_code='VND-0001',
            vendor_name='PT. Sumber Makmur Abadi',
            npwp='01.234.567.8-901.000',
            address='Jl. Industri Raya No. 15, Jakarta Timur',
            phone='021-1234567',
            email='info@sumbermakmur.co.id',
            contact_person='Budi Santoso',
            bank_name='Bank BCA',
            bank_account='1234567890'
        )
        db.session.add(vendor)
        db.session.commit()
        print('[OK] Database diinisialisasi.')
        print('[OK] User admin dibuat: admin / admin123')
        print('[OK] Demo vendor dibuat.')
    else:
        print('[!] Database sudah ada, skip init.')

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5000)
