"""
Resume API routes
"""
from fastapi import APIRouter, Depends, HTTPException, status, Request
from typing import List
from pydantic import BaseModel
from sqlalchemy.orm import Session

from ...database import SessionLocal
from ...models import Resume, User
from ...config.settings import settings
from ...services.resume_service import create_resume, get_user_resumes, get_resume_by_id, update_resume, delete_resume

router = APIRouter()

# Pydantic models for resumes
class ResumeCreate(BaseModel):
    title: str
    content: str

    class Config:
        json_schema_extra = {
            "example": {
                "title": "John Doe's Resume",
                "content": "Experienced software engineer with 5 years of experience..."
            }
        }

class ResumeUpdate(BaseModel):
    title: str = None
    content: str = None

class ResumeResponse(BaseModel):
    id: int
    user_id: int
    title: str
    content: str
    is_active: bool

    class Config:
        from_attributes = True
        json_schema_extra = {
            "example": {
                "id": 1,
                "user_id": 1,
                "title": "John Doe's Resume",
                "content": "Experienced software engineer with 5 years of experience...",
                "is_active": True
            }
        }

@router.get("/", response_model=List[ResumeResponse])
async def get_resumes(db: Session = Depends(SessionLocal), request: Request = None):
    """Get all resumes for the current user"""
    tenant_id = getattr(request.state, 'tenant_id', None)
    if not tenant_id and settings.MULTI_TENANT_ENABLED:
        raise HTTPException(status_code=400, detail="Tenant ID is required")
    
    # Extract user_id from token in a real app, for now using a default
    user_id = 1  # This would come from authentication in a real implementation
    
    # Verify user belongs to the current tenant
    user = db.query(User).filter(
        User.id == user_id,
        User.tenant_id == tenant_id
    ).first()
    if not user and settings.MULTI_TENANT_ENABLED:
        raise HTTPException(status_code=400, detail="Access denied")
    
    resumes = get_user_resumes(db, user_id, tenant_id)
    return resumes

@router.get("/{resume_id}", response_model=ResumeResponse)
async def get_resume(resume_id: int, db: Session = Depends(SessionLocal), request: Request = None):
    """Get a specific resume"""
    tenant_id = getattr(request.state, 'tenant_id', None)
    if not tenant_id and settings.MULTI_TENANT_ENABLED:
        raise HTTPException(status_code=400, detail="Tenant ID is required")
    
    # Extract user_id from token in a real app, for now using a default
    user_id = 1  # This would come from authentication in a real implementation
    
    # Verify user belongs to the current tenant
    user = db.query(User).filter(
        User.id == user_id,
        User.tenant_id == tenant_id
    ).first()
    if not user and settings.MULTI_TENANT_ENABLED:
        raise HTTPException(status_code=400, detail="Access denied")
    
    resume = get_resume_by_id(db, resume_id, user_id, tenant_id)
    if not resume:
        raise HTTPException(status_code=404, detail="Resume not found")
    return resume

@router.post("/", response_model=ResumeResponse)
async def create_user_resume(resume: ResumeCreate, db: Session = Depends(SessionLocal), request: Request = None):
    """Create a new resume for the current user"""
    tenant_id = getattr(request.state, 'tenant_id', None)
    if not tenant_id and settings.MULTI_TENANT_ENABLED:
        raise HTTPException(status_code=400, detail="Tenant ID is required")
    
    # Extract user_id from token in a real app, for now using a default
    user_id = 1  # This would come from authentication in a real implementation
    
    # Verify user belongs to the current tenant
    user = db.query(User).filter(
        User.id == user_id,
        User.tenant_id == tenant_id
    ).first()
    if not user and settings.MULTI_TENANT_ENABLED:
        raise HTTPException(status_code=400, detail="Access denied")
    
    db_resume = create_resume(db, user_id, resume.title, resume.content, tenant_id)
    return db_resume

@router.put("/{resume_id}", response_model=ResumeResponse)
async def update_user_resume(resume_id: int, resume_update: ResumeUpdate, db: Session = Depends(SessionLocal), request: Request = None):
    """Update a resume for the current user"""
    tenant_id = getattr(request.state, 'tenant_id', None)
    if not tenant_id and settings.MULTI_TENANT_ENABLED:
        raise HTTPException(status_code=400, detail="Tenant ID is required")
    
    # Extract user_id from token in a real app, for now using a default
    user_id = 1  # This would come from authentication in a real implementation
    
    # Verify user belongs to the current tenant
    user = db.query(User).filter(
        User.id == user_id,
        User.tenant_id == tenant_id
    ).first()
    if not user and settings.MULTI_TENANT_ENABLED:
        raise HTTPException(status_code=400, detail="Access denied")
    
    db_resume = update_resume(db, resume_id, user_id, tenant_id, resume_update.title, resume_update.content)
    if not db_resume:
        raise HTTPException(status_code=404, detail="Resume not found")
    return db_resume

@router.delete("/{resume_id}")
async def delete_user_resume(resume_id: int, db: Session = Depends(SessionLocal), request: Request = None):
    """Delete a resume for the current user"""
    tenant_id = getattr(request.state, 'tenant_id', None)
    if not tenant_id and settings.MULTI_TENANT_ENABLED:
        raise HTTPException(status_code=400, detail="Tenant ID is required")
    
    # Extract user_id from token in a real app, for now using a default
    user_id = 1  # This would come from authentication in a real implementation
    
    # Verify user belongs to the current tenant
    user = db.query(User).filter(
        User.id == user_id,
        User.tenant_id == tenant_id
    ).first()
    if not user and settings.MULTI_TENANT_ENABLED:
        raise HTTPException(status_code=400, detail="Access denied")
    
    success = delete_resume(db, resume_id, user_id, tenant_id)
    if not success:
        raise HTTPException(status_code=404, detail="Resume not found")
    return {"message": "Resume deleted successfully"}