from datetime import datetime, timedelta
from fastapi import APIRouter, Depends, HTTPException, Path
from sqlalchemy.orm import Session
from database import get_db
from models.models_profile_tables import RecruiterTrialStudent, StudentProfile
from models.subscription_model import RecruiterSubscription, Subscription
from schemas.student_schema import StudentProfileOut
from schemas.subscription_schema import (
    RecruiterSubscriptionCreate,
    RecruiterSubscriptionOut,
    SubscriptionCreate,
    SubscriptionOut
)

router = APIRouter()

@router.post("/create", response_model=SubscriptionOut)
def create_subscription(subscription: SubscriptionCreate, db: Session = Depends(get_db)):
    # Check for duplicate subscription name
    if db.query(Subscription).filter(Subscription.name == subscription.name).first():
        raise HTTPException(status_code=400, detail="Subscription name already exists")
    
    # Create subscription with is_trial included
    new_plan = Subscription(
        name=subscription.name,
        description=subscription.description,
        price=subscription.price,
        duration_days=subscription.duration_days,
        max_profile_views=subscription.max_profile_views,
        is_trial=subscription.is_trial  # ✅ Include is_trial
    )

    db.add(new_plan)
    db.commit()
    db.refresh(new_plan)
    return new_plan


@router.get("/all", response_model=list[SubscriptionOut])
def get_all_subscriptions(db: Session = Depends(get_db)):
    return db.query(Subscription).all()

@router.delete("/{subscription_id}")
def delete_subscription(subscription_id: int, db: Session = Depends(get_db)):
    sub = db.query(Subscription).filter(Subscription.id == subscription_id).first()
    if not sub:
        raise HTTPException(status_code=404, detail="Subscription not found")
    db.delete(sub)
    db.commit()
    return {"message": "Subscription deleted successfully"}

# ✅ Recruiter takes a subscription
@router.post("/subscribe", response_model=RecruiterSubscriptionOut)
def subscribe(data: RecruiterSubscriptionCreate, db: Session = Depends(get_db)):
    plan = db.query(Subscription).filter(Subscription.id == data.subscription_id).first()
    if not plan:
        raise HTTPException(status_code=404, detail="Subscription plan not found")

    if plan.is_trial:
        # ✅ Allow only one trial subscription per recruiter
        existing_trial = db.query(RecruiterSubscription).filter(
            RecruiterSubscription.recruiter_id == data.recruiter_id,
            RecruiterSubscription.subscription_id == plan.id
        ).first()
        if existing_trial:
            raise HTTPException(status_code=400, detail="Trial plan already used")

        start_date = datetime.now()
        end_date = start_date + timedelta(days=5)
    else:
        start_date = datetime.now()
        end_date = start_date + timedelta(days=plan.duration_days)

    # ✅ Create subscription entry
    new_sub = RecruiterSubscription(
        recruiter_id=data.recruiter_id,
        subscription_id=data.subscription_id,
        start_date=start_date,
        end_date=end_date,
        is_active=True
    )
    db.add(new_sub)
    db.commit()
    db.refresh(new_sub)

    # ✅ If trial, assign latest 5 students
    if plan.is_trial:
        latest_students = db.query(StudentProfile).order_by(StudentProfile.id.desc()).limit(5).all()

        for student in latest_students:
            trial_link = RecruiterTrialStudent(
                recruiter_id=data.recruiter_id,
                student_id=student.id
            )
            db.add(trial_link)

        db.commit()

    return new_sub

@router.get("/trial-students/{recruiter_id}", response_model=list[StudentProfileOut])
def get_trial_students(
    recruiter_id: int = Path(..., description="ID of the recruiter"),
    db: Session = Depends(get_db)
):
    student_ids = db.query(RecruiterTrialStudent.student_id).filter(
        RecruiterTrialStudent.recruiter_id == recruiter_id
    ).all()

    ids = [sid[0] for sid in student_ids]

    students = db.query(StudentProfile).filter(StudentProfile.id.in_(ids)).all()
    return students

@router.get("/recruiter/latest-data/{recruiter_id}")
def get_latest_data(recruiter_id: int, db: Session = Depends(get_db)):
    now = datetime.now()
    sub = db.query(RecruiterSubscription).filter(
        RecruiterSubscription.recruiter_id == recruiter_id,
        RecruiterSubscription.is_active == True,
        RecruiterSubscription.end_date >= now
    ).order_by(RecruiterSubscription.end_date.desc()).first()

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

    plan = db.query(Subscription).filter(Subscription.id == sub.subscription_id).first()
    query = db.query(YourDataModel).order_by(YourDataModel.created_at.desc())  # 🔁 Replace YourDataModel

    if plan and plan.is_trial:
        query = query.limit(5)

    data = query.all()
    return data

@router.post("/profile-view/{recruiter_id}")
def record_profile_view(recruiter_id: int, db: Session = Depends(get_db)):
    now = datetime.now()
    sub = db.query(RecruiterSubscription).filter(
        RecruiterSubscription.recruiter_id == recruiter_id,
        RecruiterSubscription.is_active == True
    ).order_by(RecruiterSubscription.end_date.desc()).first()

    if not sub or sub.end_date < now:
        if sub and sub.is_active:
            sub.is_active = False
            db.commit()
        raise HTTPException(status_code=403, detail="Subscription has expired")

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

    if plan.max_profile_views and sub.views_used >= plan.max_profile_views:
        sub.is_active = False
        db.commit()
        raise HTTPException(status_code=403, detail="Profile view limit exceeded")

    sub.views_used += 1

    if plan.is_trial and sub.views_used >= 5:
        sub.is_active = False
        sub.end_date = now

    db.commit()
    db.refresh(sub)

    return {
        "message": "Profile view recorded",
        "views_used": sub.views_used,
        "remaining_views": max(0, (plan.max_profile_views or 0) - sub.views_used),
        "active": sub.is_active
    }

@router.get("/status/{recruiter_id}")
def check_subscription_status(recruiter_id: int, db: Session = Depends(get_db)):
    now = datetime.now()

    subscription = db.query(RecruiterSubscription).filter(
        RecruiterSubscription.recruiter_id == recruiter_id
    ).order_by(RecruiterSubscription.end_date.desc()).first()

    if not subscription:
        return {
            "status": "inactive",
            "message": "No subscription found"
        }

    plan = db.query(Subscription).filter(Subscription.id == subscription.subscription_id).first()
    max_views = plan.max_profile_views if plan else 0

    if subscription.end_date >= now:
        days_left = (subscription.end_date - now).days
        return {
            "status": "active",
            "is_trial": plan.is_trial if plan else False,
            "start_date": subscription.start_date,
            "end_date": subscription.end_date,
            "days_left": days_left,
            "max_profile_views": max_views,
            "views_used": subscription.views_used,
            "remaining_views": max(0, max_views - subscription.views_used)
        }
    else:
        if subscription.is_active:
            subscription.is_active = False
            db.commit()
        return {
            "status": "inactive",
            "is_trial": plan.is_trial if plan else False,
            "start_date": subscription.start_date,
            "end_date": subscription.end_date,
            "max_profile_views": max_views,
            "views_used": subscription.views_used,
            "remaining_views": 0,
            "message": "Subscription expired and marked inactive"
        }
