import os
from flask import request, send_file
from app.api import api_bp
from app.services.import_export_service import create_template_excel, import_excel, export_tables
from app.utils.auth import role_required
from app.utils.response import ok, fail


@api_bp.post("/admin/import-excel")
@role_required("administrator")
def import_excel_api():
    if "file" not in request.files:
        return fail("No file provided", 400)

    file = request.files["file"]
    if not file.filename:
        return fail("No selected file", 400)

    temp_path = os.path.join(os.getcwd(), "backend", "tmp_import.xlsx")
    file.save(temp_path)

    selections = request.form.to_dict() if request.form else {}
    results = import_excel(temp_path, selections)
    os.remove(temp_path)

    return ok({"imported": results}, "Import completed")


@api_bp.get("/admin/export-database")
@role_required("administrator")
def export_database_api():
    tables = request.args.getlist("tables")
    if not tables:
        return fail("No tables selected", 400)

    output = export_tables(tables)
    return send_file(
        output,
        as_attachment=True,
        download_name="database_export.xlsx",
        mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    )


@api_bp.get("/admin/download-template")
@role_required("administrator")
def download_template_api():
    output = create_template_excel()
    return send_file(
        output,
        as_attachment=True,
        download_name="savings_plan_import_template.xlsx",
        mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    )
