from flask import Blueprint, request, jsonify
from models.client import Clients
from models.user import Users

from flask_jwt_extended import jwt_required, get_jwt_identity

clients_bp = Blueprint("clients", __name__, url_prefix="/clients")

@clients_bp.route("/", methods=["GET"])
@jwt_required()
def list_clients():
    clients_db = Clients()
    user_id = get_jwt_identity()
    users = Users()
    user = users.get_user_by_id(user_id)
    if user['user_role'] == 'company_user':
        user_id = user['company_id']
    clients = clients_db.get_all_by_user(user_id)
    return jsonify(clients), 200

@clients_bp.route("/", methods=["POST"])
@jwt_required()
def create_client():
    clients_db = Clients()
    user_id = get_jwt_identity()
    data = request.get_json()
    users = Users()
    user = users.get_user_by_id(user_id)
    if user['user_role'] == 'company_user':
        user_id = user['company_id']
    client_id = clients_db.create(
        user_id=user_id,
        name=data["name"],
        address=data["address"],
        register_number=data["register_number"],
        contact_person=data["contact_person"],
        phone=data["phone"],
        email=data["email"],
        vat = data["vat"]
    )
    return jsonify({"message": "Client created", "id": client_id}), 201

@clients_bp.route("/<int:client_id>", methods=["PUT"])
@jwt_required()
def update_client(client_id):
    clients_db = Clients()
    data = request.get_json()
    name=data["name"]
    address=data["address"]
    register_number=data["register_number"]
    contact_person=data["contact_person"]
    phone=data["phone"]
    email=data["email"]
    vat = data["vat"]
    clients_db.update(client_id, name, address, register_number, contact_person, phone, email, vat)
    return jsonify({"message": "Client updated"}), 200

@clients_bp.route("/<int:client_id>", methods=["DELETE"])
@jwt_required()
def delete_client(client_id):
    clients_db = Clients()
    success = clients_db.delete(client_id)
    if not success:
        return jsonify({"message": "Client not found or unauthorized"}), 404
    return jsonify({"message": "Client deleted"}), 200

@clients_bp.route("/<int:client_id>", methods=["GET"])
@jwt_required()
def get_client(client_id):
    clients_db = Clients()
    client = clients_db.get_by_id(client_id)
    if not client:
        return jsonify({"message": "Client not found"}), 404
    return jsonify(client), 200