from flask import Blueprint, make_response, redirect, render_template, request, url_for

from src.internals.database.database import get_cursor
from src.lib.files import get_file_relationships

files_bp = Blueprint("files", __name__)


@files_bp.route("/search_hash", methods=["GET", "POST"])
def search_hash():
    file_hash = request.args.get("hash")
    if file_hash:
        if not (len(file_hash) == 64 and all(c in "0123456789abcdefABCDEF" for c in file_hash)):
            return redirect(url_for("files.search_hash"))
        file_data: dict | None = get_file_relationships(file_hash)
        for discord_post in (file_data["discord_posts"] or []) if file_data else []:
            cursor = get_cursor()
            cursor.execute(
                "SELECT * FROM discord_channels WHERE channel_id = %s",
                (discord_post["channel"],),
            )
            lookup_result = cursor.fetchall()
            discord_post["channel_name"] = lookup_result[0]["name"] if len(lookup_result) else ""
        response = make_response(
            render_template(
                "search_results.html",
                hash=file_hash,
                file_data=file_data,
                props={"currentPage": "search_hash"},
            )
        )
        response.headers["Cache-Control"] = "s-maxage=60"
    else:
        response = make_response(
            render_template(
                "search_hash.html",
                props={"currentPage": "search_hash"},
            ),
            200,
        )
        response.headers["Cache-Control"] = "s-maxage=60"

    return response
