from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from typing import List
from pydantic import BaseModel
from app.db.session import get_db
from app.db.models import User, Tenant
from app.core.security import verify_password, get_password_hash, create_access_token
from app.api.schemas import UserLogin, UserRegister, Token, TokenWithUser
from app.api.deps import get_current_user

router = APIRouter(prefix="/auth", tags=["auth"])


class IndustryOption(BaseModel):
    id: str
    name: str
    description: str
    icon: str


@router.get("/industries", response_model=List[IndustryOption])
def get_industries():
    """Получить список доступных отраслей для регистрации"""
    industries = [
        {
            "id": "medicine",
            "name": "Медицина",
            "description": "Клиники, стоматология, ветеринария",
            "icon": "🏥"
        },
        {
            "id": "beauty",
            "name": "Красота и здоровье",
            "description": "Салоны красоты, SPA, фитнес",
            "icon": "💄"
        },
        {
            "id": "autoservice",
            "name": "Автосервис",
            "description": "СТО, автомойки, автосалоны",
            "icon": "🚗"
        },
        {
            "id": "delivery",
            "name": "Доставка",
            "description": "Курьерские службы, рестораны",
            "icon": "🚚"
        },
        {
            "id": "education",
            "name": "Образование",
            "description": "Онлайн-школы, курсы, репетиторы",
            "icon": "📚"
        },
        {
            "id": "retail",
            "name": "Ритейл",
            "description": "Магазины, интернет-магазины",
            "icon": "🛍️"
        },
        {
            "id": "services",
            "name": "Услуги",
            "description": "Консультации, ремонт, уборка",
            "icon": "🔧"
        },
        {
            "id": "other",
            "name": "Другое",
            "description": "Другая сфера деятельности",
            "icon": "📋"
        }
    ]
    
    return industries


@router.post("/register", response_model=TokenWithUser)
def register(data: UserRegister, db: Session = Depends(get_db)):
    # Check if user exists
    existing_user = db.query(User).filter(User.email == data.email).first()
    if existing_user:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Email already registered",
        )
    
    # Create tenant
    tenant = Tenant(name=data.tenant_name, industry=data.industry, status="active")
    db.add(tenant)
    db.flush()
    
    # Create user
    user = User(
        tenant_id=tenant.id,
        email=data.email,
        password_hash=get_password_hash(data.password),
        role="user",
    )
    db.add(user)
    db.commit()
    db.refresh(user)
    
    # Install industry templates for the selected industry
    install_industry_templates(tenant.id, data.industry, db)
    
    # Generate token
    access_token = create_access_token(data={"sub": user.id, "tenant_id": tenant.id})
    return TokenWithUser(
        access_token=access_token,
        user={
            "id": user.id,
            "email": user.email,
            "role": user.role,
            "tenant_id": user.tenant_id
        }
    )


def install_industry_templates(tenant_id: int, industry: str, db: Session):
    """Установить готовые шаблоны для индустрии при регистрации"""
    from app.db.models import IndustryTemplate, UserIndustryTemplate
    
    # Получаем шаблоны для данной индустрии
    templates = db.query(IndustryTemplate).filter(
        IndustryTemplate.industry == industry
    ).all()
    
    # Создаем пользовательские шаблоны
    for template in templates:
        user_template = UserIndustryTemplate(
            tenant_id=tenant_id,
            industry_template_id=template.id,
            is_active=True,
            channels=template.channels,
            is_custom=False
        )
        db.add(user_template)
    
    db.commit()


@router.post("/login", response_model=TokenWithUser)
def login(data: UserLogin, db: Session = Depends(get_db)):
    user = db.query(User).filter(User.email == data.email).first()
    if not user or not verify_password(data.password, user.password_hash):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Неверный email или пароль",
        )
    
    access_token = create_access_token(data={"sub": user.id, "tenant_id": user.tenant_id})
    return TokenWithUser(
        access_token=access_token,
        user={
            "id": user.id,
            "email": user.email,
            "role": user.role,
            "tenant_id": user.tenant_id
        }
    )


@router.get("/me")
def get_current_user_info(current_user: User = Depends(get_current_user)):
    """Получить информацию о текущем пользователе"""
    return {
        "id": current_user.id,
        "email": current_user.email,
        "role": current_user.role,
        "tenant_id": current_user.tenant_id
    }




