from fastapi import APIRouter, Depends, HTTPException, Body
from sqlalchemy.orm import Session
from database import SessionLocal
from models.service_model import Service, ServiceCategory, ServiceStatus
from models.models_profile_tables import RecruiterProfile
from datetime import datetime
from typing import List, Optional
from pydantic import BaseModel
from models.user_model import User

router = APIRouter()

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

class ServiceCreate(BaseModel):
    company_logo: Optional[str] = None
    company_name: str
    company_rating: Optional[float] = None
    job_title: str
    job_location: str
    salary_inr: Optional[str] = None
    salary_usd: Optional[str] = None
    job_type: Optional[str] = None
    job_description: str
    responsibilities: Optional[List[str]] = None
    requirements: Optional[List[str]] = None
    tech_stack: Optional[List[str]] = None
    benefits: Optional[List[str]] = None
    apply_link: Optional[str] = None
    service_category: Optional[ServiceCategory] = None

class ServiceUpdate(BaseModel):
    company_logo: Optional[str] = None
    company_name: Optional[str] = None
    company_rating: Optional[float] = None
    job_title: Optional[str] = None
    job_location: Optional[str] = None
    salary_inr: Optional[str] = None
    salary_usd: Optional[str] = None
    job_type: Optional[str] = None
    job_description: Optional[str] = None
    responsibilities: Optional[List[str]] = None
    requirements: Optional[List[str]] = None
    tech_stack: Optional[List[str]] = None
    benefits: Optional[List[str]] = None
    apply_link: Optional[str] = None
    service_category: Optional[ServiceCategory] = None
    status: Optional[ServiceStatus] = None

# ➕ Add service
@router.post("/recruiter/services/{email}")
def add_service(email: str, service: ServiceCreate, db: Session = Depends(get_db)):
    recruiter = (
        db.query(RecruiterProfile)
        .join(User, RecruiterProfile.user_id == User.id)
        .filter(User.email == email, User.role == "recruiter")
        .first()
    )
    if not recruiter:
        raise HTTPException(status_code=404, detail="Recruiter profile not found")

    new_service = Service(
        recruiter_id=recruiter.id,
        company_logo=service.company_logo,
        company_name=service.company_name,
        company_rating=service.company_rating,
        job_title=service.job_title,
        job_location=service.job_location,
        salary_inr=service.salary_inr,
        salary_usd=service.salary_usd,
        job_type=service.job_type,
        job_description=service.job_description,
        responsibilities="|".join(service.responsibilities) if service.responsibilities else None,
        requirements="|".join(service.requirements) if service.requirements else None,
        tech_stack="|".join(service.tech_stack) if service.tech_stack else None,
        benefits="|".join(service.benefits) if service.benefits else None,
        apply_link=service.apply_link,
        service_category=service.service_category,
        status=ServiceStatus.ACTIVE,
        created_at=datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    )
    try:
        db.add(new_service)
        db.commit()
        db.refresh(new_service)
        return {"message": "Service added successfully", "service": new_service}
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=400, detail=str(e))

# 📥 Get recruiter services
@router.get("/recruiter/services/{email}")
def get_recruiter_services(
    email: str,
    category: Optional[ServiceCategory] = None,
    status: Optional[ServiceStatus] = None,
    db: Session = Depends(get_db)
):
    recruiter = (
        db.query(RecruiterProfile)
        .join(User, RecruiterProfile.user_id == User.id)
        .filter(User.email == email, User.role == "recruiter")
        .first()
    )
    if not recruiter:
        raise HTTPException(status_code=404, detail="Recruiter profile not found")

    query = db.query(Service).filter(Service.recruiter_id == recruiter.id)
    if category:
        query = query.filter(Service.service_category == category)
    if status:
        query = query.filter(Service.status == status)
    services = query.all()
    # Parse delimited fields back to lists
    for s in services:
        s.responsibilities = s.responsibilities.split("|") if s.responsibilities else []
        s.requirements = s.requirements.split("|") if s.requirements else []
        s.tech_stack = s.tech_stack.split("|") if s.tech_stack else []
        s.benefits = s.benefits.split("|") if s.benefits else []
    return services

# ✏️ Update service
@router.put("/recruiter/services/{service_id}")
def update_service(service_id: int, service_update: ServiceUpdate, db: Session = Depends(get_db)):
    service = db.query(Service).filter(Service.id == service_id).first()
    if not service:
        raise HTTPException(status_code=404, detail="Service not found")

    try:
        update_data = service_update.dict(exclude_unset=True)
        # Handle list fields
        for key in ["responsibilities", "requirements", "tech_stack", "benefits"]:
            if key in update_data and update_data[key] is not None:
                update_data[key] = "|".join(update_data[key])
        for key, value in update_data.items():
            setattr(service, key, value)
        service.updated_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        db.commit()
        db.refresh(service)
        return {"message": "Service updated successfully", "service": service}
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=400, detail=str(e))

# ❌ Delete service
@router.delete("/recruiter/services/{service_id}")
def delete_service(service_id: int, db: Session = Depends(get_db)):
    service = db.query(Service).filter(Service.id == service_id).first()
    if not service:
        raise HTTPException(status_code=404, detail="Service not found")

    try:
        db.delete(service)
        db.commit()
        return {"message": "Service deleted successfully"}
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=400, detail=str(e))