import re


class ImportHelper:
    @staticmethod
    def validate_row(row: dict):
        """
        Kiểm tra tính hợp lệ của từng dòng đơn hàng.
        Theo logic mới:
        - orderId KHÔNG còn là trường bắt buộc
        - backend sẽ tự sinh orderId cuối cùng
        - mỗi dòng cần đủ dữ liệu để backend gộp theo customer + address
        """
        errors = []

        # Các trường bắt buộc tối thiểu để import
        required_fields = ["customer", "items", "address"]

        for field in required_fields:
            value = row.get(field)
            if value is None or str(value).strip() == "":
                errors.append(f"Thiếu trường bắt buộc: {field}")

        # Bắt buộc phải có productId hoặc style để tạo item
        product_id = str(row.get("productId") or "").strip()
        style = str(row.get("style") or "").strip()
        if not product_id and not style:
            errors.append("Thiếu trường bắt buộc: productId")

        # Kiểm tra định dạng Email nếu có
        email = str(row.get("email") or "").strip()
        if email and not re.match(r"[^@]+@[^@]+\.[^@]+", email):
            errors.append("Định dạng Email không hợp lệ")

        return errors

    @staticmethod
    def map_excel_to_schema(row: dict):
        """
        Map các cột từ file Excel thực tế sang schema hệ thống cần.
        Giữ orderId là optional nếu file người dùng có cung cấp.
        Nếu không có, backend sẽ tự sinh.
        """
        order_id = row.get("Order ID") or row.get("orderId") or ""

        customer = row.get("toName") or row.get("customer") or ""
        style = row.get("Style") or row.get("style") or ""
        size = row.get("Size") or row.get("size") or ""
        qty = row.get("QTY") or row.get("Qty") or row.get("quantity") or 1

        street = row.get("toStreet1") or row.get("street") or ""
        city = row.get("toCity") or row.get("city") or ""
        state = row.get("toState") or row.get("state") or ""
        zip_code = row.get("toZip") or row.get("zipCode") or row.get("zip") or ""
        country = row.get("toCountry") or row.get("country") or ""

        address_parts = [street, city, state, zip_code, country]
        address = ", ".join([str(part).strip() for part in address_parts if str(part).strip()])

        return {
            "orderId": str(order_id).strip(),
            "productId": str(row.get("SKU") or row.get("sku") or row.get("productId") or "").strip(),
            "productName": str(row.get("Product Name") or row.get("productName") or "").strip(),
            "customer": str(customer).strip(),
            "items": f"{style} - {size} (Qty: {qty})".strip(),
            "address": address,
            "phone": row.get("Phone") or row.get("phone") or "",
            "email": row.get("email", "") or "",
            "style": str(style).strip(),
            "quantity": qty,
            "price": row.get("Price", 0) or row.get("price", 0) or 0,
            "shipping": row.get("Shipping", 0) or row.get("shipping", 0) or 0,
            "tax": row.get("Tax", 0) or row.get("tax", 0) or 0,
            "color": row.get("Color") or row.get("color") or "",
            "size": str(size).strip(),
            "design": row.get("Design URL") or row.get("design") or "",
            "status": "Unpaid",
        }