import frappe
from frappe import _

@frappe.whitelist()
def quick_sell(serial_no, customer=None, payment_method='Cash'):
    """Create Sales Invoice for quick cash sale."""
    try:
        serial = frappe.get_doc('Serial No', serial_no)
        
        if serial.r2_status != 'Ready for Sale':
            return {'error': 'Device must be Ready for Sale'}
        
        # Use default customer if none provided
        if not customer:
            customer = frappe.db.get_value('Customer', {}, 'name', order_by='creation asc')
            if not customer:
                # Create walk-in customer
                customer = frappe.get_doc({
                    'doctype': 'Customer',
                    'customer_name': 'Walk-in Customer',
                    'customer_type': 'Individual'
                }).insert(ignore_permissions=True).name
        
        # Create Sales Invoice
        price = serial.assigned_price or serial.suggested_price or 0
        
        invoice = frappe.get_doc({
            'doctype': 'Sales Invoice',
            'customer': customer,
            'serial_no': serial_no,
            'device_condition': f"Cosmetic: {serial.cosmetic_grade or 'N/A'}",
            'posting_date': frappe.utils.today(),
            'due_date': frappe.utils.today(),
            'items': [{
                'item_code': serial.item_code,
                'qty': 1,
                'rate': price,
                'amount': price,
                'serial_no': serial_no
            }],
            'payments': [{
                'mode_of_payment': payment_method,
                'amount': price
            }]
        })
        invoice.insert(ignore_permissions=True)
        invoice.submit()
        
        # Update Serial No
        serial.r2_status = 'Sold'
        serial.status = 'Delivered'
        serial.customer = customer
        serial.save(ignore_permissions=True)
        
        return {
            'success': True,
            'invoice': invoice.name,
            'customer': customer,
            'amount': price
        }
        
    except Exception as e:
        frappe.log_error(f"Quick sell failed: {str(e)}", "Sales")
        return {'error': str(e)}

@frappe.whitelist()
def create_sales_order(quotation_name):
    """Create Sales Order from Quotation."""
    try:
        from erpnext.selling.doctype.quotation.quotation import make_sales_order
        
        so = make_sales_order(quotation_name)
        so.insert(ignore_permissions=True)
        so.submit()
        
        return {'success': True, 'sales_order': so.name}
    except Exception as e:
        return {'error': str(e)}

@frappe.whitelist()
def create_delivery_note(sales_order_name):
    """Create Delivery Note from Sales Order."""
    try:
        from erpnext.selling.doctype.sales_order.sales_order import make_delivery_note
        
        dn = make_delivery_note(sales_order_name)
        dn.insert(ignore_permissions=True)
        dn.submit()
        
        return {'success': True, 'delivery_note': dn.name}
    except Exception as e:
        return {'error': str(e)}
