"""Customer Journey Test - Tests all customer-facing pages via Django test Client."""
import os, sys, json
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dropship.settings')

import django
django.setup()

from django.test import Client
from products.models import Product, Category, Brand
from accounts.models import Customer

c = Client()
p = Product.objects.filter(is_active=True).first()
cat = Category.objects.filter(is_active=True).first()
brand = Brand.objects.filter(is_active=True).first()

results = []

def test(label, r):
    ok = r.status_code in (200, 302, 301)
    tag = 'OK' if ok else 'FAIL'
    results.append((label, r.status_code, ok))
    print(f'  [{tag}] {label}: {r.status_code}')
    return ok

all_ok = True

print('='*60)
print('GUEST FLOW')
print('='*60)

print('\n--- Browsing ---')
all_ok &= test('Product listing', c.get('/products/'))
all_ok &= test('Category browse', c.get(f'/products/?category={cat.id}'))
all_ok &= test('Product detail', c.get(f'/products/{p.slug}/'))
all_ok &= test('Search results', c.get('/products/?q=phone'))
all_ok &= test('Sort price_asc', c.get('/products/?sort=price_asc'))
all_ok &= test('Sort newest', c.get('/products/?sort=newest'))
all_ok &= test('Price filter', c.get('/products/?min_price=10&max_price=50'))
all_ok &= test('Rating filter', c.get('/products/?rating=4'))
all_ok &= test('In stock filter', c.get('/products/?in_stock=1'))

if brand:
    all_ok &= test('Brand page', c.get(f'/products/brand/{brand.slug}/'))
else:
    print('  [SKIP] Brand page: no brands')

all_ok &= test('Deals page', c.get('/products/deals/'))
all_ok &= test('New arrivals', c.get('/products/new-arrivals/'))
all_ok &= test('Best sellers', c.get('/products/best-sellers/'))
all_ok &= test('Compare page', c.get('/products/compare/'))
all_ok &= test('Quick view', c.get(f'/products/quick-view/{p.id}/'))

print('\n--- Cart Flow ---')
all_ok &= test('Add to cart', c.post('/cart/add/', {'product_id': str(p.id), 'quantity': '1'}, HTTP_X_REQUESTED_WITH='XMLHttpRequest'))
all_ok &= test('Cart page', c.get('/cart/'))
all_ok &= test('Mini cart', c.get('/cart/mini/', HTTP_X_REQUESTED_WITH='XMLHttpRequest'))
all_ok &= test('Coupon apply (invalid)', c.post('/cart/coupon/apply/', {'code': 'INVALID'}))
all_ok &= test('Coupon remove', c.post('/cart/coupon/remove/'))
all_ok &= test('Checkout (guest)', c.get('/checkout/'))

print('\n--- Info Pages ---')
all_ok &= test('About', c.get('/about/'))
all_ok &= test('FAQ', c.get('/faq/'))
all_ok &= test('Contact GET', c.get('/contact/'))
all_ok &= test('Contact POST', c.post('/contact/', {'name':'Test','email':'t@t.com','subject':'Hi','message':'Hello'}))
all_ok &= test('Shipping', c.get('/shipping-policy/'))
all_ok &= test('Returns', c.get('/returns-refund/'))
all_ok &= test('Terms', c.get('/terms-conditions/'))
all_ok &= test('Privacy', c.get('/privacy-policy/'))
all_ok &= test('Cookies', c.get('/cookie-policy/'))

print('\n--- Features ---')
r = c.post('/currency/set/', json.dumps({"currency":"EUR"}), content_type='application/json', HTTP_X_REQUESTED_WITH='XMLHttpRequest')
all_ok &= test('Currency switch', r)
r = c.post('/country/set/', json.dumps({"country":"DE"}), content_type='application/json', HTTP_X_REQUESTED_WITH='XMLHttpRequest')
all_ok &= test('Country switch', r)
all_ok &= test('Search autocomplete', c.get('/products/api/search-suggestions/?q=phone'))
all_ok &= test('Flash sale API', c.get('/products/api/flash-sale/'))
all_ok &= test('Recently viewed API', c.get('/products/api/recently-viewed/'))
all_ok &= test('Newsletter', c.post('/newsletter/subscribe/', {'email':'test@test.com'}, HTTP_X_REQUESTED_WITH='XMLHttpRequest'))
all_ok &= test('Sitemap', c.get('/sitemap.xml'))
all_ok &= test('Wishlist (guest - redirects)', c.post('/account/wishlist/toggle/', {'product_id': str(p.id)}, HTTP_X_REQUESTED_WITH='XMLHttpRequest'))

print('\n' + '='*60)
print('LOGGED-IN FLOW')
print('='*60)

user, _ = Customer.objects.get_or_create(username='testcustomer', defaults={'email':'test@test.com','first_name':'Test','is_active':True})
user.set_password('test1234')
user.save()
c.login(username='testcustomer', password='test1234')

print('\n--- Account Pages ---')
all_ok &= test('Dashboard', c.get('/account/'))
all_ok &= test('Orders list', c.get('/account/orders/'))
all_ok &= test('Wishlist', c.get('/account/wishlist/'))
all_ok &= test('Recently viewed', c.get('/account/recently-viewed/'))
all_ok &= test('Notifications', c.get('/account/notifications/'))
all_ok &= test('Addresses', c.get('/account/addresses/'))
all_ok &= test('Support', c.get('/account/support/'))
all_ok &= test('Edit profile', c.get('/account/profile/'))

print('\n--- Auth Cart/Checkout ---')
all_ok &= test('Add to cart (auth)', c.post('/cart/add/', {'product_id': str(p.id), 'quantity': '1'}, HTTP_X_REQUESTED_WITH='XMLHttpRequest'))
all_ok &= test('Cart (auth)', c.get('/cart/'))
all_ok &= test('Checkout (auth)', c.get('/checkout/'))

print('\n--- Auth Features ---')
all_ok &= test('Wishlist toggle (auth)', c.post('/account/wishlist/toggle/', {'product_id': str(p.id)}, HTTP_X_REQUESTED_WITH='XMLHttpRequest'))
all_ok &= test('View product (auth)', c.get(f'/products/{p.slug}/'))
all_ok &= test('Recently viewed API (auth)', c.get('/products/api/recently-viewed/'))
all_ok &= test('Compare add (auth)', c.post('/products/compare/add/', {'product_id': str(p.id)}, HTTP_X_REQUESTED_WITH='XMLHttpRequest'))
all_ok &= test('Quick view (auth)', c.get(f'/products/quick-view/{p.id}/'))

print('\n' + '='*60)
passed = sum(1 for _,_,ok in results if ok)
total = len(results)
failed = [(l,s) for l,s,ok in results if not ok]
print(f'RESULTS: {passed}/{total} passed')
if failed:
    print('\nFAILED:')
    for label, status in failed:
        print(f'  - {label}: {status}')
else:
    print('\nALL TESTS PASSED!')
print('='*60)
