from typing import List, Optional
from datetime import datetime
from pydantic import BaseModel
from enum import Enum

class MappingStrategy(str, Enum):
    SKIP = "SKIP"
    OVERWRITE = "OVERWRITE"

class MappingRowStatus(str, Enum):
    NEW = "NEW"          # User exists, no mapping exists -> Ready to insert
    UPDATE = "UPDATE"    # User exists, mapping exists -> Ready to update (if overwrite)
    ERROR = "ERROR"      # Invalid format or other error
    AUTO_CREATE_USER = "AUTO_CREATE_USER" # User does not exist -> Create User + Mapping

class MappingRowPreview(BaseModel):
    row_index: int
    mobile: str
    mapped_key: str
    mapped_email: Optional[str] = None
    status: MappingRowStatus
    message: Optional[str] = None
    user_id: Optional[int] = None

class MappingPreviewResponse(BaseModel):
    total_rows: int
    valid_count: int
    error_count: int
    new_count: int
    update_count: int
    preview_rows: List[MappingRowPreview]

class MappingImportSummary(BaseModel):
    total_processed: int
    inserted: int
    updated: int
    failed: int

class ImportLogItem(BaseModel):
    import_time: datetime
    mobile: str
    mapped_key: Optional[str]
    status: str  # "Success" or "Failed"
    message: Optional[str] = None # Failure reason or success detail
    is_unified_account_created: bool = False
    generated_password: Optional[str] = None
    mapped_email: Optional[str] = None

class ImportLogResponse(BaseModel):
    summary: MappingImportSummary
    logs: List[ImportLogItem]

class MappingCreate(BaseModel):
    mobile: str
    mapped_key: Optional[str] = None
    mapped_email: Optional[str] = None
    password: str # Admin password for verification

class MappingUpdate(BaseModel):
    mapped_key: Optional[str] = None
    mapped_email: Optional[str] = None
    is_active: Optional[bool] = None
    password: str  # Required for verification

class MappingDelete(BaseModel):
    password: str

class MappingResponse(BaseModel):
    id: int
    app_id: int
    user_id: int
    mapped_key: Optional[str] = None
    mapped_email: Optional[str] = None
    user_name: Optional[str] = None
    user_mobile: str  # Convenient to have
    user_status: str  # Added: Unified Account Status
    is_active: bool = True
    new_user_created: bool = False
    generated_password: Optional[str] = None

    class Config:
        from_attributes = True

class MappingList(BaseModel):
    total: int
    items: List[MappingResponse]
