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

from ..models import Application, JobPosting, Resume
from ..config.settings import settings


def create_application(db: Session, user_id: int, job_posting_id: int, resume_id: int, 
                      cover_letter: str = None, tenant_id: int = None) -> Application:
    """
    Create a new job application
    """
    # Verify that the resume belongs to the user
    resume = db.query(Resume).filter(
        Resume.id == resume_id,
        Resume.user_id == user_id
    ).first()
    if not resume:
        raise ValueError("Resume does not belong to user")
    
    # In a multi-tenant setup, we should verify tenant access to the job posting
    if settings.MULTI_TENANT_ENABLED and tenant_id:
        job_posting = db.query(JobPosting).filter(
            JobPosting.id == job_posting_id,
            JobPosting.tenant_id == tenant_id
        ).first()
        if not job_posting:
            raise ValueError("Job posting not found in tenant")
    
    db_application = Application(
        user_id=user_id,
        job_posting_id=job_posting_id,
        resume_id=resume_id,
        cover_letter=cover_letter
    )
    db.add(db_application)
    db.commit()
    db.refresh(db_application)
    return db_application


def get_user_applications(db: Session, user_id: int) -> List[Application]:
    """
    Get all applications for a specific user
    """
    return db.query(Application).filter(Application.user_id == user_id).all()


def get_job_applications(db: Session, job_posting_id: int, tenant_id: int = None) -> List[Application]:
    """
    Get all applications for a specific job posting within a tenant
    """
    query = db.query(Application).join(JobPosting).filter(Application.job_posting_id == job_posting_id)
    
    if settings.MULTI_TENANT_ENABLED and tenant_id:
        query = query.filter(JobPosting.tenant_id == tenant_id)
    
    return query.all()


def get_application_by_id(db: Session, application_id: int, user_id: int = None, 
                         job_posting_id: int = None) -> Optional[Application]:
    """
    Get a specific application by ID with optional user or job constraints
    """
    query = db.query(Application).filter(Application.id == application_id)
    
    if user_id:
        query = query.filter(Application.user_id == user_id)
    if job_posting_id:
        query = query.filter(Application.job_posting_id == job_posting_id)
    
    return query.first()


def update_application_status(db: Session, application_id: int, status: str, 
                            user_id: int = None, job_posting_id: int = None) -> Optional[Application]:
    """
    Update application status
    """
    query = db.query(Application).filter(Application.id == application_id)
    
    if user_id:
        query = query.filter(Application.user_id == user_id)
    if job_posting_id:
        query = query.filter(Application.job_posting_id == job_posting_id)
    
    db_application = query.first()
    if not db_application:
        return None
    
    db_application.status = status
    db.commit()
    db.refresh(db_application)
    return db_application


def delete_application(db: Session, application_id: int, user_id: int = None) -> bool:
    """
    Delete an application
    """
    query = db.query(Application).filter(Application.id == application_id)
    
    if user_id:
        query = query.filter(Application.user_id == user_id)
    
    db_application = query.first()
    if not db_application:
        return False
    
    db.delete(db_application)
    db.commit()
    return True