import os
from werkzeug.utils import secure_filename
from flask import current_app
from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from models.user import Users

profile_bp = Blueprint("profile", __name__)


@profile_bp.route("/", methods=["GET"])
@jwt_required()
def get_profile():
    user_id = get_jwt_identity()
    users = Users()
    user = users.get_user_by_id(user_id)  # Plain SQL method returning dict or None

    if not user:
        return jsonify({"error": "User not found"}), 404

    return jsonify({
        "id": user["id"],
        "name": user["name"],
        "contact_name": user["contact_name"],
        "email": user["email"],
        "address": user["address"],
        "register_number": user["register_number"],
        "phone": user["phone"],
        "logo_filename": user["logo_filename"],
        "terms": user["terms"],
        "first_order_number": user["first_order_number"],
        "user_role": user["user_role"],
        "vat":user["vat"],
        "company_id":user['company_id']
    })


@profile_bp.route("/", methods=["PUT"])
@jwt_required()
def update_profile():
    users = Users()
    user_id = get_jwt_identity()
    user = users.get_user_by_id(user_id)
    if not user:
        return jsonify({"error": "User not found"}), 404

    data = request.get_json()
    update_data = {
        "name": data.get("name", user["name"]),
        "contact_name": data.get("contact_name", user["contact_name"]),
        "email": data.get("email", user["email"]),
        "address": data.get("address", user["address"]),
        "register_number": data.get("register_number", user["register_number"]),
        "phone": data.get("phone", user["phone"]),
        "logo_filename": data.get("logo_filename", user["logo_filename"]),
        "terms": data.get("terms", user["terms"]),
        "first_order_number": data.get("first_order_number", user["first_order_number"]),
        "user_id": user_id,
        "vat":data.get("vat", user["vat"]),
    }
    users.update_user(update_data)

    return jsonify({"message": "Profile updated successfully"})


@profile_bp.route("/logo", methods=["POST"])
@jwt_required()
def upload_logo():
    users = Users()
    if 'logo' not in request.files:
        return jsonify({"error": "Logo file is required"}), 400

    file = request.files['logo']
    if file.filename == '':
        return jsonify({"error": "No selected file"}), 400

    filename = secure_filename(file.filename)
    upload_dir = os.path.join(current_app.root_path, '..', 'instance', 'logos')
    os.makedirs(upload_dir, exist_ok=True)

    filepath = os.path.join(upload_dir, filename)
    file.save(filepath)

    user_id = get_jwt_identity()
    user = users.get_user_by_id(user_id)
    if not user:
        return jsonify({"error": "User not found"}), 404

    # Update the logo filename in DB
    users.update_user_logo(user_id, {"logo_filename": filename})

    return jsonify({"message": "Logo uploaded", "filename": filename}), 200

@profile_bp.route('/email')
@jwt_required()
def get_email_credentials():
    user_id = get_jwt_identity()
    users = Users()

    credentials = users.get_email_credentials(user_id)
    if not credentials:
        return jsonify({"error": "Credentials not found"}), 404
    
    return jsonify({
        'id': credentials['id'],
        'user_id': credentials['user_id'],
        'smtp_host': credentials['smtp_host'],
        'smtp_port': credentials['smtp_port'],
        'smtp_user': credentials['smtp_user'],
        'created_at': credentials['created_at']
    }), 200

@profile_bp.route('/email', methods=["POST"])
@jwt_required()
def insert_email_credentials():
    users = Users()
    user_id = get_jwt_identity()

    data = request.get_json()
    if not data:
        return jsonify({"error": "Credentials not found"}), 404
    smtp_host = data['smtp_host']
    smtp_port = data['smtp_port']
    smtp_user = data['smtp_user']

    users.insert_email_credentials(user_id, smtp_host, smtp_port, smtp_user)

    return jsonify({"message": "Credentials inserted successfully"}), 200

@profile_bp.route('/email', methods=["PUT"])
@jwt_required()
def update_email_credentials():
    users = Users()
    user_id = get_jwt_identity()

    data = request.get_json()
    if not data:
        return jsonify({"error": "Credentials not found"}), 404
    smtp_host = data['smtp_host']
    smtp_port = data['smtp_port']
    smtp_user = data['smtp_user']

    users.update_email_credentials(user_id, smtp_host, smtp_port, smtp_user)

    return jsonify({"message": "Credentials updated successfully"}), 200