from flask import Blueprint, request, jsonify, render_template
from flask_jwt_extended import jwt_required, get_jwt_identity
from models.publications.articles import Articles, ArticleModel
from models.users import Users
from models.audit import Audit, AuditModel

articles_bp = Blueprint("articles", __name__)
audit = Audit()

@articles_bp.route("/editor", methods=["GET"])
@jwt_required()
def show_editor():
    token = request.args.get("token", "")
    article_id = request.args.get("article_id", "None")
    return render_template("editor.html", token=token, article_id=article_id)

@articles_bp.route("/", methods=["GET"])
@jwt_required()
def get_all_articles():
    articles_repo = Articles()
    articles = articles_repo.get_all_articles()
    return jsonify([vars(a) for a in articles]), 200

@articles_bp.route("/<int:article_id>", methods=["GET"])
@jwt_required()
def get_article(article_id):
    articles_repo = Articles()
    article = articles_repo.get_article(article_id)
    if not article:
        return jsonify({"error": "Articolul nu a fost gasit"}), 404
    return jsonify(vars(article)), 200

@articles_bp.route("/add", methods=["POST"])
@jwt_required()
def add_article():
    current_user_id = int(get_jwt_identity())
    user_repo = Users()
    user = user_repo.get_user(current_user_id)
    
    if not user:
        return jsonify({"error": "Utilizatorul nu a fost gasit"}), 404
        
    # Verifică dacă utilizatorul are permisiunea de a crea articole
    if not getattr(user, 'can_create_articles', 0) == 1:
        audit.new_entry(AuditModel(user_id=current_user_id, action="Attempt to add article without permission", status="403 - Forbidden"))
        return jsonify({"error": "Nu aveti permisiunea de a publica articole"}), 403

    data = request.get_json()
    title = data.get("title")
    content = data.get("content")

    if not title or not content:
        return jsonify({"error": "Titlul si continutul sunt obligatorii"}), 400

    articles_repo = Articles()
    article_id = articles_repo.add_article(title, content, current_user_id)
    
    if article_id:
        audit.new_entry(AuditModel(user_id=current_user_id, action=f"Added article: {title}", status="201 - Created"))
        return jsonify({"message": "Articol adaugat cu succes", "id": article_id}), 201
        
    return jsonify({"error": "Eroare la adaugarea articolului"}), 500

@articles_bp.route("/update/<int:article_id>", methods=["PUT"])
@jwt_required()
def update_article(article_id):
    current_user_id = int(get_jwt_identity())
    articles_repo = Articles()
    article = articles_repo.get_article(article_id)
    
    if not article:
        return jsonify({"error": "Articolul nu a fost gasit"}), 404
        
    # Permite modificarea doar dacă utilizatorul curent este autorul articolului
    if article.author_id != current_user_id:
        audit.new_entry(AuditModel(user_id=current_user_id, action=f"Attempt to update article ID {article_id} owned by other user", status="403 - Forbidden"))
        return jsonify({"error": "Puteti modifica doar articolele scrise de dumneavoastra"}), 403

    data = request.get_json()
    title = data.get("title")
    content = data.get("content")

    if not title or not content:
        return jsonify({"error": "Titlul si continutul sunt obligatorii"}), 400

    if articles_repo.update_article(article_id, title, content):
        audit.new_entry(AuditModel(user_id=current_user_id, action=f"Updated article ID: {article_id}", status="200 - OK"))
        return jsonify({"message": "Articol modificat cu succes"}), 200
        
    return jsonify({"error": "Nu s-a putut modifica articolul"}), 500

@articles_bp.route("/delete/<int:article_id>", methods=["DELETE"])
@jwt_required()
def delete_article(article_id):
    current_user_id = int(get_jwt_identity())
    articles_repo = Articles()
    article = articles_repo.get_article(article_id)
    
    if not article:
        return jsonify({"error": "Articolul nu a fost gasit"}), 404
        
    # Permite ștergerea doar dacă utilizatorul curent este autorul articolului
    if article.author_id != current_user_id:
        audit.new_entry(AuditModel(user_id=current_user_id, action=f"Attempt to delete article ID {article_id} owned by other user", status="403 - Forbidden"))
        return jsonify({"error": "Puteti sterge doar articolele scrise de dumneavoastra"}), 403

    if articles_repo.delete_article(article_id):
        audit.new_entry(AuditModel(user_id=current_user_id, action=f"Deleted article ID: {article_id}", status="200 - OK"))
        return jsonify({"message": "Articol sters cu succes"}), 200
        
    return jsonify({"error": "Nu s-a putut sterge articolul"}), 500
