
import os
import sys
import json
import django
from decimal import Decimal

# Setup Django
sys.path.append(os.getcwd())
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings")
django.setup()

from django.test import RequestFactory
from django.contrib.auth import get_user_model
from django.db import connection

from customers.models import Customer
from inventory.models import Warehouse, Sale
from products.models import Product, UnitOfMeasure
from pos.views import pos_checkout
from orders.models import OrderStatus

def run():
    # Setup Data
    User = get_user_model()
    user = User.objects.first()
    if not user:
        print("No user found")
        return

    # Create/Get Customer
    customer, _ = Customer.objects.get_or_create(
        name="Test Customer",
        defaults={'phone': '+375291112233'}
    )

    # Create/Get Warehouse
    warehouse, _ = Warehouse.objects.get_or_create(
        name="Test Warehouse",
        defaults={'is_active': True}
    )

    # Create product
    product, _ = Product.objects.get_or_create(
        name="Test Product Debug",
        defaults={
            'sku': 'DEBUG001',
            'buying_price': 10,
            'actual_price': 50,
            'warehouse': warehouse
        }
    )
    product.actual_price = 50
    product.save()

    # Ensure OrderStatus exists
    OrderStatus.objects.get_or_create(code='completed', is_system=True, defaults={'name': 'Completed', 'is_positive_end': True})
    OrderStatus.objects.get_or_create(code='draft', is_system=True, defaults={'name': 'Draft'})

    # Prepare Request
    factory = RequestFactory()
    
    payload = {
        "customer_id": customer.id,
        "warehouse_id": warehouse.id,
        "items": [
            {
                "type": "product",
                "id": product.id,
                "quantity": 1,
                "price": 100.00,  # Custom price
                "quantity_base": 1
            }
        ],
        "payments": [
            {"payment_method": "cash", "amount": 100.00}
        ],
        "notes": "Debug Sale"
    }

    request = factory.post(
        '/pos/api/checkout/',
        data=json.dumps(payload),
        content_type='application/json'
    )
    request.user = user

    print("Executing pos_checkout...")
    response = pos_checkout(request)
    print(f"Response: {response.content}")

    # Verify Sale
    sales = Sale.objects.filter(product=product).order_by('-id')[:1]
    if sales:
        sale = sales[0]
        print(f"Sale created. ID: {sale.id}")
        print(f"Sale Quantity: {sale.quantity}")
        print(f"Sale Price: {sale.sale_price}")
        if sale.sale_price == 0:
            print("FAILURE: Sale price is 0!")
        else:
            print(f"SUCCESS: Sale price is {sale.sale_price}")
    else:
        print("FAILURE: No Sale created!")

if __name__ == "__main__":
    from django_tenants.utils import schema_context
    # Replace with actual schema name if needed, assuming 'public' for now or the default tenant
    # Since I don't know the tenant, I'll try to run in the current context.
    # But usually need to set schema.
    # Let's try to find a tenant.
    from tenants.models import Client
    tenant = Client.objects.first()
    if tenant:
        print(f"Running in tenant: {tenant.schema_name}")
        with schema_context(tenant.schema_name):
            run()
    else:
        print("No tenant found, running in public?")
        run()
