import urllib.parse
from sqlalchemy.orm import Session
from app.models.order import Order
from app.models.product import Product
from app.repositories.order import order_repository
from app.core.exceptions import BadRequestException
from typing import List, Optional

class OrderService:
    """Service layer handling checkout orders and formatting WhatsApp messages."""

    def checkout(
        self,
        db: Session,
        *,
        customer_name: str,
        customer_phone: str,
        shipping_address: str,
        items: List[dict],
        user_id: Optional[str] = None
    ) -> Order:
        """Create new transaction record and generate client WhatsApp direct checkout link."""
        if not items:
            raise BadRequestException("Cart is empty. Must include at least 1 item.")

        # 1. Instansiasi order header model
        order = Order(
            user_id=user_id,
            status="pending",
            total_price=0.0,
            customer_name=customer_name,
            customer_phone=customer_phone,
            shipping_address=shipping_address
        )

        # 2. Simpan order beserta relasi items & potong stok di repo
        saved_order = order_repository.create_order_with_items(
            db, 
            order_obj=order, 
            items_in=items
        )

        # 3. Generate Link WhatsApp berisi detail transaksi
        whatsapp_link = self._generate_whatsapp_link(saved_order)
        saved_order.whatsapp_link = whatsapp_link
        
        # Simpan link ke DB
        db.add(saved_order)
        db.commit()
        db.refresh(saved_order)
        
        return saved_order

    def _generate_whatsapp_link(self, order: Order) -> str:
        """Create custom URL-encoded WhatsApp direct text block containing invoice details."""
        # Gunakan nomor admin dummy di kode, bisa diubah via settings kelak
        admin_number = "628123456789" # Ganti dengan nomor WhatsApp Toko Anda
        
        message = (
            f"Halo Admin, saya ingin konfirmasi pesanan perhiasan.\n\n"
            f"*Detail Pesanan:*\n"
            f"• ID Pesanan: `{str(order.id)[:8]}`\n"
            f"• Nama Pembeli: {order.customer_name}\n"
            f"• No HP: {order.customer_phone}\n"
            f"• Alamat Kirim: {order.shipping_address}\n\n"
            f"*Daftar Barang:*\n"
        )

        for item in order.items:
            product_name = item.product.name
            material = item.product.material.capitalize()
            qty = item.quantity
            price_formatted = f"Rp {int(item.price):,}".replace(",", ".")
            subtotal_formatted = f"Rp {int(item.price * qty):,}".replace(",", ".")
            message += f"- {product_name} ({material}) x{qty} @ {price_formatted} = {subtotal_formatted}\n"

        total_formatted = f"Rp {int(order.total_price):,}".replace(",", ".")
        message += f"\n*Total Tagihan:* *{total_formatted}*\n\n"
        message += "Mohon info rekening pembayaran dan estimasi ongkir ya min. Terima kasih!"

        encoded_message = urllib.parse.quote(message)
        return f"https://api.whatsapp.com/send?phone={admin_number}&text={encoded_message}"

    def get_order_by_id(self, db: Session, order_id: str) -> Order:
        order = order_repository.get(db, id=order_id)
        if not order:
            raise BadRequestException("Order not found.")
        return order

    def get_user_order_history(self, db: Session, user_id: str) -> List[Order]:
        return order_repository.get_user_orders(db, user_id=user_id)

order_service = OrderService()
