#!/usr/bin/env python
"""
Create API test data for billing endpoints
All test records are marked with 'API_TEST' in name/description/notes
"""
import os
import sys
import django

# Setup Django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'igny8_core.settings')
django.setup()

from django.utils import timezone
from django.contrib.auth import get_user_model
from igny8_core.auth.models import Account, Plan
from igny8_core.business.billing.models import (
    Invoice, Payment, CreditTransaction, AccountPaymentMethod, PaymentMethodConfig
)
from decimal import Decimal
from datetime import timedelta

User = get_user_model()

print("Creating API test data...")

# Get or create test account
try:
    account = Account.objects.get(name__icontains='scale')
    print(f"✓ Using existing account: {account.name} (ID: {account.id})")
except Account.DoesNotExist:
    # Get a plan
    plan = Plan.objects.filter(is_active=True).first()
    account = Account.objects.create(
        name='API_TEST_ACCOUNT',
        slug='api-test-account',
        plan=plan,
        credits=5000,
        status='active'
    )
    print(f"✓ Created test account: {account.name} (ID: {account.id})")

# Create test invoices
invoice1, created = Invoice.objects.get_or_create(
    account=account,
    invoice_number='INV-API-TEST-001',
    defaults={
        'status': 'pending',
        'subtotal': Decimal('99.99'),
        'tax': Decimal('0.00'),
        'total': Decimal('99.99'),
        'currency': 'USD',
        'invoice_date': timezone.now().date(),
        'due_date': (timezone.now() + timedelta(days=30)).date(),
        'billing_email': 'test@igny8.com',
        'notes': 'API_TEST: Invoice for approval test',
        'line_items': [{'description': 'API Test Service', 'amount': 99.99, 'quantity': 1}],
    }
)
if created:
    print(f"✓ Created test invoice 1 (ID: {invoice1.id})")
else:
    print(f"✓ Existing test invoice 1 (ID: {invoice1.id})")

invoice2, created = Invoice.objects.get_or_create(
    account=account,
    invoice_number='INV-API-TEST-002',
    defaults={
        'status': 'pending',
        'subtotal': Decimal('49.99'),
        'tax': Decimal('0.00'),
        'total': Decimal('49.99'),
        'currency': 'USD',
        'invoice_date': timezone.now().date(),
        'due_date': (timezone.now() + timedelta(days=30)).date(),
        'billing_email': 'test@igny8.com',
        'notes': 'API_TEST: Invoice for rejection test',
        'line_items': [{'description': 'API Test Service', 'amount': 49.99, 'quantity': 1}],
    }
)
if created:
    print(f"✓ Created test invoice 2 (ID: {invoice2.id})")
else:
    print(f"✓ Existing test invoice 2 (ID: {invoice2.id})")

# Create test payment for approval
pending_payment, created = Payment.objects.get_or_create(
    account=account,
    invoice=invoice1,
    manual_reference='API_TEST_REF_001',
    defaults={
        'status': 'pending_approval',
        'payment_method': 'bank_transfer',
        'amount': Decimal('99.99'),
        'currency': 'USD',
        'manual_notes': 'API_TEST: Test payment for approval endpoint',
    }
)
if created:
    print(f"✓ Created pending payment (ID: {pending_payment.id}) for approve_payment endpoint")
else:
    print(f"✓ Existing pending payment (ID: {pending_payment.id})")

# Create test payment for rejection
reject_payment, created = Payment.objects.get_or_create(
    account=account,
    invoice=invoice2,
    manual_reference='API_TEST_REF_002',
    defaults={
        'status': 'pending_approval',
        'payment_method': 'manual',
        'amount': Decimal('49.99'),
        'currency': 'USD',
        'manual_notes': 'API_TEST: Test payment for rejection endpoint',
    }
)
if created:
    print(f"✓ Created pending payment (ID: {reject_payment.id}) for reject_payment endpoint")
else:
    print(f"✓ Existing pending payment (ID: {reject_payment.id})")

# Get or create test payment method config
configs = PaymentMethodConfig.objects.filter(payment_method='bank_transfer')
if configs.exists():
    config = configs.first()
    print(f"✓ Using existing payment method config (ID: {config.id})")
    created = False
else:
    config = PaymentMethodConfig.objects.create(
        payment_method='bank_transfer',
        display_name='API_TEST Bank Transfer',
        instructions='API_TEST: Transfer to account 123456789',
        is_enabled=True,
        sort_order=1,
    )
    print(f"✓ Created payment method config (ID: {config.id})")
    created = True

# Create test account payment method
account_method, created = AccountPaymentMethod.objects.get_or_create(
    account=account,
    type='bank_transfer',
    defaults={
        'display_name': 'API_TEST Account Bank Transfer',
        'instructions': 'API_TEST: Test account-specific payment method',
        'is_default': True,
    }
)
if created:
    print(f"✓ Created account payment method (ID: {account_method.id})")
else:
    print(f"✓ Existing account payment method (ID: {account_method.id})")

# Create test credit transaction
transaction, created = CreditTransaction.objects.get_or_create(
    account=account,
    transaction_type='adjustment',
    amount=1000,
    defaults={
        'balance_after': account.credits,
        'description': 'API_TEST: Test credit adjustment',
        'metadata': {'test': True, 'reason': 'API testing'},
    }
)
if created:
    print(f"✓ Created credit transaction (ID: {transaction.id})")
else:
    print(f"✓ Existing credit transaction (ID: {transaction.id})")

print("\n" + "="*60)
print("API Test Data Summary:")
print("="*60)
print(f"Account ID: {account.id}")
print(f"Pending Payment (approve): ID {pending_payment.id}")
print(f"Pending Payment (reject): ID {reject_payment.id}")
print(f"Payment Method Config: ID {config.id}")
print(f"Account Payment Method: ID {account_method.id}")
print(f"Credit Transaction: ID {transaction.id}")
print("="*60)
print("\nTest endpoints:")
print(f"POST /v1/admin/billing/{pending_payment.id}/approve_payment/")
print(f"POST /v1/admin/billing/{reject_payment.id}/reject_payment/")
print(f"POST /v1/admin/users/{account.id}/adjust-credits/")
print(f"GET  /v1/billing/payment-methods/{account_method.id}/set_default/")
print("="*60)
