<?php

namespace OtomaticAi\Utils;

use Exception;
use OtomaticAi\Database\Migrator;
use OtomaticAi\Models\Netlinking;
use OtomaticAi\Models\Publication;
use OtomaticAi\Vendors\Carbon\Carbon;
use OtomaticAi\Vendors\Illuminate\Support\Arr;

class Issues
{
    public static function detect()
    {
        $issues = [];

        if (defined('DISABLE_WP_CRON') && DISABLE_WP_CRON) {
            $issues[] = [
                "key" => "cron",
                "error" => "La constante DISABLE_WP_CRON est définie sur true. L'appel par défaut de WP-Cron est désactivé. Assurez-vous d'avoir défini une autre méthode de planification des tâches.",
                "repair_link" => "http://discord.gg/QS6jDaHZ"
            ];
        }

        $issue = self::checkDatabase();
        if (!empty($issue)) {
            $issues[] = $issue;
        }

        $issue = self::checkOpenAISignature();
        if (!empty($issue)) {
            $issues[] = $issue;
        }

        $issue = self::checkNotStartedPublications();
        if (!empty($issue)) {
            $issues[] = $issue;
        }

        return $issues;
    }

    public static function repair()
    {
        if (Arr::get($_GET, "issue") === "database") {
            delete_option(OTOMATIC_AI_DB_VERSION_OPTION);
            Migrator::run();

            $issue = self::checkDatabase();
            if (!empty($issue)) {
                echo "Some tables are still missing. Please check your WordPress and database error files.";
            } else {
                echo "All tables have been created.";
            }
        }
    }

    private static function checkDatabase()
    {
        global $wpdb;

        $otomaticTables = [
            $wpdb->prefix . "otomatic_ai_linkings",
            $wpdb->prefix . "otomatic_ai_netlinking",
            $wpdb->prefix . "otomatic_ai_personas",
            $wpdb->prefix . "otomatic_ai_projects",
            $wpdb->prefix . "otomatic_ai_publications",
            $wpdb->prefix . "otomatic_ai_single_mode_generations",
            $wpdb->prefix . "otomatic_ai_templates",
            $wpdb->prefix . "otomatic_ai_usages",
        ];

        $localTables = $wpdb->get_results("SHOW TABLES", ARRAY_N);
        $localTables = array_map(function ($table) {
            return $table[0];
        }, $localTables);

        $diffTables = array_diff($otomaticTables, $localTables);

        if (count($diffTables) > 0) {
            return [
                "key" => "database",
                "error" => "Les tables " . implode(", ", $diffTables) . " sont manquantes.",
                "repair_link" => admin_url('admin.php?page=otomatic-ai-repair&issue=database'),
                "missing_tables" => $diffTables,
            ];
        }
    }

    private static function checkOpenAISignature()
    {
        try {
            $response = Auth::validateOpenAISignature(Settings::get("api.openai.api_key"));
            if (!Arr::get($response, "success", false)) {
                return [
                    "key" => "openai_signature",
                    "error" => "Votre clé API OpenAI ne peut pas être activée. otomatic.ai n'autorise qu'une seule clé API par compte.",
                ];
            }
        } catch (Exception $e) {
        }
    }

    private static function checkNotStartedPublications()
    {
        $publicationsCounts = Publication::idle()
            ->whereRelation('project', 'enabled', true)
            ->where("published_at", "<=", Carbon::now()->subMinutes(60))
            ->count();

        if ($publicationsCounts > 0) {
            return [
                "key" => "not_started_publications",
                "error" => "Il y a " . $publicationsCounts . " publications non démarrées depuis plus de 5 minutes. Un problème de tâche CRON WordPress peut être à l'origine de ce problème.",
            ];
        }

        $netlinkingCounts = Netlinking::idle()
            ->where("updated_at", "<=", Carbon::now()->subMinutes(60))
            ->count();

        if ($netlinkingCounts > 0) {
            return [
                "key" => "not_started_publications",
                "error" => "Il y a " . $netlinkingCounts . " campagnes de Netlinking non démarrées depuis plus de 5 minutes. Un problème de tâche CRON WordPress peut être à l'origine de ce problème.",
            ];
        }
    }
}
