from sqlalchemy import Column, Integer, String, Boolean, DateTime, ForeignKey, Text, Float
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
import uuid
import hashlib
from ..database import Base


def generate_dealer_code():
    """Generate a unique 6-character dealer code"""
    unique_id = uuid.uuid4().hex
    return "D" + hashlib.sha256(unique_id.encode()).hexdigest()[:5].upper()


class DealerApplication(Base):
    """Dealer application for users wanting to become dealers"""
    __tablename__ = "dealer_applications"

    id = Column(Integer, primary_key=True, index=True)
    user_id = Column(Integer, ForeignKey("users.id"), nullable=False)

    # Business info
    business_name = Column(String(100), nullable=False)  # 상호명
    business_number = Column(String(50), nullable=True)  # 사업자번호 (선택)

    # Personal info
    real_name = Column(String(100), nullable=False)  # 실명
    id_number_encrypted = Column(String(255), nullable=True)  # 주민번호/외국인번호 (암호화)
    phone = Column(String(50), nullable=False)  # 연락처

    # Bank info for withdrawals
    bank_name = Column(String(50), nullable=False)  # 은행명
    bank_account = Column(String(100), nullable=False)  # 계좌번호
    account_holder = Column(String(100), nullable=False)  # 예금주명

    # Photo
    photo_url = Column(String(500), nullable=True)  # 본인 사진 URL

    # Application status
    status = Column(String(20), default="pending")  # pending, approved, rejected
    rejected_reason = Column(Text, nullable=True)  # 거부 사유

    # Timestamps
    applied_at = Column(DateTime(timezone=True), server_default=func.now())
    approved_at = Column(DateTime(timezone=True), nullable=True)

    # Relationships
    user = relationship("User", back_populates="dealer_application")


class DealerInfo(Base):
    """Approved dealer information"""
    __tablename__ = "dealer_info"

    id = Column(Integer, primary_key=True, index=True)
    user_id = Column(Integer, ForeignKey("users.id"), unique=True, nullable=False)

    # Dealer identification
    dealer_code = Column(String(10), unique=True, index=True, nullable=False)  # 딜러 고유 코드 (D + 5자리)
    dealer_card_url = Column(String(500), nullable=True)  # 딜러증 이미지 URL

    # Business info (from application)
    business_name = Column(String(100), nullable=False)
    real_name = Column(String(100), nullable=False)
    phone = Column(String(50), nullable=False)
    photo_url = Column(String(500), nullable=True)

    # Bank info (from application)
    bank_name = Column(String(50), nullable=False)
    bank_account = Column(String(100), nullable=False)
    account_holder = Column(String(100), nullable=False)

    # Earnings
    total_commission_earned = Column(Float, default=0.0)  # 총 수수료 수익 (KRW)
    total_withdrawn = Column(Float, default=0.0)  # 총 출금액 (KRW)
    pending_withdrawal = Column(Float, default=0.0)  # 출금 대기 금액 (KRW)

    # Status
    is_active = Column(Boolean, default=True)

    # Timestamps
    created_at = Column(DateTime(timezone=True), server_default=func.now())

    # Relationships
    user = relationship("User", back_populates="dealer_info")
