"""
Resume management service
"""
from typing import List, Optional
from sqlalchemy.orm import Session

from ..models import Resume, User
from ..config.settings import settings


def create_resume(db: Session, user_id: int, title: str, content: str, tenant_id: int) -> Resume:
    """
    Create a new resume for a user
    """
    db_resume = Resume(
        user_id=user_id,
        title=title,
        content=content,
        tenant_id=tenant_id
    )
    db.add(db_resume)
    db.commit()
    db.refresh(db_resume)
    return db_resume


def get_user_resumes(db: Session, user_id: int, tenant_id: int = None) -> List[Resume]:
    """
    Get all resumes for a specific user
    """
    query = db.query(Resume).filter(Resume.user_id == user_id)
    
    if settings.MULTI_TENANT_ENABLED and tenant_id:
        query = query.filter(Resume.tenant_id == tenant_id)
    
    return query.all()


def get_resume_by_id(db: Session, resume_id: int, user_id: int, tenant_id: int = None) -> Optional[Resume]:
    """
    Get a specific resume by ID for a user
    """
    query = db.query(Resume).filter(
        Resume.id == resume_id,
        Resume.user_id == user_id
    )
    
    if settings.MULTI_TENANT_ENABLED and tenant_id:
        query = query.filter(Resume.tenant_id == tenant_id)
    
    return query.first()


def update_resume(db: Session, resume_id: int, user_id: int, tenant_id: int = None, title: str = None, content: str = None) -> Optional[Resume]:
    """
    Update a resume
    """
    query = db.query(Resume).filter(
        Resume.id == resume_id,
        Resume.user_id == user_id
    )
    
    if settings.MULTI_TENANT_ENABLED and tenant_id:
        query = query.filter(Resume.tenant_id == tenant_id)
    
    db_resume = query.first()
    
    if not db_resume:
        return None
    
    if title is not None:
        db_resume.title = title
    if content is not None:
        db_resume.content = content
    
    db.commit()
    db.refresh(db_resume)
    return db_resume


def delete_resume(db: Session, resume_id: int, user_id: int, tenant_id: int = None) -> bool:
    """
    Delete a resume
    """
    query = db.query(Resume).filter(
        Resume.id == resume_id,
        Resume.user_id == user_id
    )
    
    if settings.MULTI_TENANT_ENABLED and tenant_id:
        query = query.filter(Resume.tenant_id == tenant_id)
    
    db_resume = query.first()
    
    if not db_resume:
        return False
    
    db.delete(db_resume)
    db.commit()
    return True