from sqlalchemy import BigInteger, String, Integer, Index, ForeignKey, JSON
from sqlalchemy.dialects.mysql import TINYINT
from sqlalchemy.orm import Mapped, mapped_column
from typing import Optional
from app.core.models.base import Base, TimestampMixin, TenantMixin


class CustomerAddress(Base, TenantMixin, TimestampMixin):
    """顾客收货地址"""

    __tablename__ = "customer_addresses"
    __table_args__ = (
        Index("ix_customer_addr_customer", "customer_id"),
        Index("ix_customer_addr_default", "is_default"),
        Index("ix_customer_addr_tenant", "tenant_id"),
        {
            "mysql_engine": "InnoDB",
            "mysql_charset": "utf8mb4",
            "mysql_collate": "utf8mb4_unicode_ci",
        },
    )

    id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
    customer_id: Mapped[int] = mapped_column(BigInteger, ForeignKey("customers.id", ondelete="CASCADE"), nullable=False)
    name: Mapped[str] = mapped_column(String(50), nullable=False, comment="收货人姓名")
    phone: Mapped[str] = mapped_column(String(20), nullable=False, comment="手机号")
    country: Mapped[str] = mapped_column(String(2), nullable=False, default="NZ", comment="ISO 3166-1 alpha-2 国家代码，如 NZ/AU/CN")
    province: Mapped[str] = mapped_column(String(100), nullable=False, comment="省/州/地区")
    city: Mapped[str] = mapped_column(String(100), nullable=False, comment="城市")
    district: Mapped[str] = mapped_column(String(100), nullable=False, default="", comment="区县（可选）")
    street: Mapped[str] = mapped_column(String(200), nullable=False, comment="详细街道地址")
    zip_code: Mapped[str] = mapped_column(String(20), nullable=False, default="", comment="邮政编码")
    is_default: Mapped[int] = mapped_column(TINYINT(1), nullable=False, default=0, comment="是否默认地址")
    sort_order: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
    extra_fields: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True, comment="自定义字段值")

    def __repr__(self) -> str:
        return f"<CustomerAddress id={self.id} customer_id={self.customer_id} name={self.name!r}>"