"""Interventions Planning Routes - GMAO Collège"""
from flask import Blueprint, render_template, redirect, url_for, request, flash, jsonify
from flask_login import login_required, current_user
from app_new.extensions import db
from ..core.models.maintenance import Intervention, InterventionComment
from ..core.models.equipment import Equipment
from ..core.models.user import User
from datetime import datetime

planning_bp = Blueprint("interventions_planning", __name__, url_prefix="/interventions", template_folder="templates")

@planning_bp.route('/planning')
@login_required
def planning():
    """Compatibilité : redirige vers le planning unifié."""
    params = {}
    if request.args.get('year', type=int):
        params['year'] = request.args.get('year', type=int)
    return redirect(url_for('planning.index', **params))


@planning_bp.route('/<int:id>/delete', methods=['POST'])
@login_required
def delete(id):
    """Archiver une intervention sans détruire son historique."""
    intervention = Intervention.query.get_or_404(id)
    intervention.is_deleted = True
    intervention.deleted_at = datetime.utcnow()
    intervention.deleted_by_id = current_user.id
    db.session.commit()
    flash('Intervention placée dans la corbeille. Son historique est conservé.', 'success')
    return redirect(url_for('interventions.index'))


@planning_bp.route('/<int:id>/restore', methods=['POST'])
@login_required
def restore(id):
    """Restaurer une intervention depuis la corbeille."""
    intervention = Intervention.query.get_or_404(id)
    if not intervention.is_deleted:
        flash("Cette intervention n'est pas dans la corbeille.", 'warning')
        return redirect(url_for('interventions.detail', id=intervention.id))
    
    intervention.is_deleted = False
    intervention.deleted_at = None
    intervention.deleted_by_id = None
    db.session.commit()
    flash('Intervention restaurée.', 'success')
    return redirect(url_for('interventions.detail', id=intervention.id))
