"""
Services Routes - GMAO Collège
Gestion des services du collège
"""
from flask import Blueprint, render_template, request, flash, redirect, url_for
from flask_login import login_required
from app_new.extensions import db
from ..core.models.company import Service
from ..core.models.maintenance import Lot, LotService

services_bp = Blueprint('services', __name__)

@services_bp.route('/')
@login_required
def index():
    """Liste des services."""
    page = request.args.get('page', 1, type=int)
    services = Service.query.order_by(Service.name).paginate(page=page, per_page=20)
    lot_counts = dict(
        db.session.query(LotService.service_id, db.func.count(LotService.id))
        .group_by(LotService.service_id).all()
    )
    return render_template('services/index.html', services=services, lot_counts=lot_counts)

@services_bp.route('/<int:id>')
@login_required
def detail(id):
    """Détail d'un service."""
    service = Service.query.get_or_404(id)
    lot_ids = [row.lot_id for row in LotService.query.filter_by(service_id=id).all()]
    lots = Lot.query.filter(Lot.id.in_(lot_ids)).order_by(Lot.name).paginate(per_page=50) if lot_ids else Lot.query.filter(Lot.id == -1).paginate(per_page=50)
    all_lots = Lot.query.filter(~Lot.id.in_(lot_ids)).order_by(Lot.name).all() if lot_ids else Lot.query.order_by(Lot.name).all()
    return render_template('services/detail.html', service=service, lots=lots, all_lots=all_lots)


@services_bp.route('/new', methods=['GET', 'POST'])
@login_required
def create():
    """Créer un service."""
    if request.method == 'POST':
        service = Service(
            name=request.form.get('name'),
            description=request.form.get('description'),
        )
        db.session.add(service)
        db.session.commit()
        flash('Service créé avec succès.', 'success')
        return redirect(url_for('services.index'))
    
    return render_template('services/new.html')


@services_bp.route('/<int:id>/edit', methods=['GET', 'POST'])
@login_required
def edit(id):
    service = Service.query.get_or_404(id)
    if request.method == 'POST':
        service.name = (request.form.get('name') or '').strip()
        service.description = request.form.get('description')
        service.is_active = request.form.get('is_active') == 'on'
        db.session.commit()
        flash('Service mis à jour.', 'success')
        return redirect(url_for('services.detail', id=id))
    return render_template('services/new.html', service=service)


@services_bp.route('/<int:id>/lots', methods=['POST'])
@login_required
def assign_lot(id):
    Service.query.get_or_404(id)
    added = 0
    for lot_id in request.form.getlist('lot_ids[]', type=int):
        if Lot.query.get(lot_id) and not LotService.query.filter_by(service_id=id, lot_id=lot_id).first():
            db.session.add(LotService(service_id=id, lot_id=lot_id))
            added += 1
    db.session.commit()
    flash(f'{added} lot(s) assigné(s).', 'success')
    return redirect(url_for('services.detail', id=id))


@services_bp.route('/<int:id>/lots/<int:lot_id>/remove', methods=['POST'])
@login_required
def remove_lot(id, lot_id):
    association = LotService.query.filter_by(service_id=id, lot_id=lot_id).first_or_404()
    db.session.delete(association)
    db.session.commit()
    flash('Lot retiré du service.', 'success')
    return redirect(url_for('services.detail', id=id))
