# routers/recruiter_profile_view_routes.py

from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from database import get_db
from models.profile_view_model import ProfileView
from models.user_model import User  # your main user model
from models.subscription_model import RecruiterSubscription, Subscription
from datetime import datetime
from schemas.profile_view_schema import ProfileViewCreate, ProfileViewOut

router = APIRouter(prefix="/recruiter", tags=["Recruiter Profile Views"])

# ✅ Track profile view
@router.post("/view-profile", response_model=ProfileViewOut)
def view_user_profile(view: ProfileViewCreate, db: Session = Depends(get_db)):
    # ✅ Validate recruiter
    recruiter = db.query(User).filter(User.id == view.recruiter_id, User.role == "recruiter").first()
    if not recruiter:
        raise HTTPException(status_code=403, detail="Invalid recruiter ID")

    # ✅ Validate target user
    target_user = db.query(User).filter(User.id == view.user_id, User.role == "user").first()
    if not target_user:
        raise HTTPException(status_code=404, detail="Target user not found")

    # ✅ Get latest active subscription
    now = datetime.now()
    subscription = db.query(RecruiterSubscription).join(Subscription).filter(
        RecruiterSubscription.recruiter_id == view.recruiter_id,
        RecruiterSubscription.is_active == True,
        RecruiterSubscription.start_date <= now,
        RecruiterSubscription.end_date >= now
    ).order_by(RecruiterSubscription.end_date.desc()).first()

    if not subscription:
        raise HTTPException(status_code=403, detail="No active subscription found.")

    plan = db.query(Subscription).filter(Subscription.id == subscription.subscription_id).first()
    if not plan:
        raise HTTPException(status_code=404, detail="Subscription plan not found")

    # ✅ Enforce view limit
    if subscription.views_used >= plan.max_profile_views:
        raise HTTPException(status_code=403, detail="Profile view limit reached.")

    # ✅ Prevent duplicate view
    existing = db.query(ProfileView).filter_by(
        recruiter_id=view.recruiter_id, user_id=view.user_id
    ).first()
    if existing:
        return existing

    # ✅ Save view
    new_view = ProfileView(
        recruiter_id=view.recruiter_id,
        user_id=view.user_id
    )
    db.add(new_view)

    # ✅ Increment view count
    subscription.views_used += 1

    db.commit()
    db.refresh(new_view)

    return new_view
# ✅ Count profile views by recruiter
@router.get("/profile-views/count/{recruiter_id}")
def count_profile_views(recruiter_id: int, db: Session = Depends(get_db)):
    count = db.query(ProfileView).filter(ProfileView.recruiter_id == recruiter_id).count()
    return {"recruiter_id": recruiter_id, "profiles_viewed": count}

# ✅ Fetch all users with role == "user"
@router.get("/all-users")
def get_all_users(db: Session = Depends(get_db)):
    users = db.query(User).filter(User.role == "user").all()
    return users
