"""Functions for addition of device via api rather than browser"""

from flask import Blueprint, request, current_app, jsonify
from src.in_io import sqlite as pysql
from src.http.auth import verify_api_key
from src.http.services.device_service import validate_devices, save_devices_to_db

devices_bp = Blueprint("devices", __name__)


@devices_bp.route("/api/devices", methods=["POST"])
def register_devices():
    auth = verify_api_key()
    if auth:
        return auth

    if "sqlite" not in current_app.handler.save_dict:
        return jsonify({"error": "Database not configured"}), 409

    json_data = request.get_json(silent=True)
    if not json_data:
        return jsonify({"error": "Invalid or missing JSON"}), 400

    validated, error = validate_devices(json_data.get("devices", []))
    if error:
        return jsonify({"error": error}), 422

    dberror, connection, cursor = pysql.connect_db(
        current_app.handler.save_dict["sqlite"]["db_path"], db_create=1
    )
    if dberror != 0:
        return jsonify({"error": f"Database error: {dberror}"}), 500

    if not save_devices_to_db(cursor, connection, validated["devices"]):
        return jsonify({"error": "Failed to insert devices"}), 500

    return jsonify({"message": "Devices registered", "data": validated}), 200
