from flask import Blueprint, request, jsonify
from flask_login import login_required, current_user
from app.extensions import db
from app.models.view_profile import ViewProfile

views_bp = Blueprint('views', __name__)

@views_bp.route('/api/profiles', methods=['GET'])
@login_required
def list_profiles():
    view_type = request.args.get('view_type', 'lv')
    profiles = ViewProfile.query.filter_by(
        user_id=current_user.id, view_type=view_type
    ).order_by(ViewProfile.is_default.desc(), ViewProfile.name).all()
    return jsonify([{
        'id': p.id, 'name': p.name, 'is_default': p.is_default,
        'config': p.get_config()
    } for p in profiles])

@views_bp.route('/api/profiles', methods=['POST'])
@login_required
def save_profile():
    data = request.get_json() or {}
    name = data.get('name', '').strip()
    view_type = data.get('view_type', 'lv')
    config = data.get('config', {})
    is_default = data.get('is_default', False)

    if not name:
        return jsonify({'error': 'Name erforderlich'}), 400

    existing = ViewProfile.query.filter_by(
        user_id=current_user.id, name=name, view_type=view_type
    ).first()
    if existing:
        existing.set_config(config)
        existing.is_default = is_default or existing.is_default
    else:
        existing = ViewProfile(
            user_id=current_user.id, name=name,
            view_type=view_type, is_default=is_default
        )
        existing.set_config(config)
        db.session.add(existing)

    if is_default:
        ViewProfile.query.filter_by(
            user_id=current_user.id, view_type=view_type
        ).filter(ViewProfile.id != existing.id).update({'is_default': False})

    db.session.commit()
    return jsonify({'id': existing.id, 'name': existing.name})

@views_bp.route('/api/profiles/<int:profile_id>', methods=['GET'])
@login_required
def get_profile(profile_id):
    p = ViewProfile.query.get_or_404(profile_id)
    if p.user_id != current_user.id:
        return jsonify({'error': 'Zugriff verweigert'}), 403
    return jsonify({
        'id': p.id, 'name': p.name, 'view_type': p.view_type,
        'is_default': p.is_default, 'config_json': p.get_config()
    })

@views_bp.route('/api/profiles/<int:profile_id>', methods=['PUT'])
@login_required
def update_profile(profile_id):
    p = ViewProfile.query.get_or_404(profile_id)
    if p.user_id != current_user.id:
        return jsonify({'error': 'Zugriff verweigert'}), 403
    data = request.get_json() or {}
    if 'name' in data and data['name']:
        p.name = data['name'].strip()
    if 'config_json' in data:
        p.set_config(data['config_json'])
    if 'is_default' in data:
        p.is_default = data['is_default']
    db.session.commit()
    return jsonify({'id': p.id, 'name': p.name})

@views_bp.route('/api/profiles/<int:profile_id>', methods=['DELETE'])
@login_required
def delete_profile(profile_id):
    p = ViewProfile.query.get_or_404(profile_id)
    if p.user_id != current_user.id:
        return jsonify({'error': 'Zugriff verweigert'}), 403
    if p.is_default:
        return jsonify({'error': 'Standard kann nicht gelöscht werden'}), 400
    db.session.delete(p)
    db.session.commit()
    return jsonify({'status': 'ok'})
