// logger.js
import { WebhookClient } from "discord.js";
import fs from "fs";
import path from "path";

// تحميل config.json
const configPath = path.join(process.cwd(), "config.json");
const rawData = fs.readFileSync(configPath, "utf8");
const config = JSON.parse(rawData);

let webhook = null;
if (config.webhookUrl) {
  try {
    webhook = new WebhookClient({ url: config.webhookUrl });
  } catch (e) {
    console.error("❌ Invalid webhook URL in config.json");
    webhook = null;
  }
}

/**
 * يرسل اللوج إلى الـ Webhook إذا كان موجود
 */
export async function sendLogToWebhook(payload) {
  if (!webhook) return;
  try {
    if (typeof payload === "string") {
      await webhook.send({ content: payload });
    } else if (typeof payload === "object") {
      await webhook.send(payload);
    }
  } catch (e) {
    console.error("❌ Webhook send failed:", e);
  }
}

/**
 * يرسل اللوج إلى قناة اللوج (بديلة للويبهوك)
 */
export async function sendLogToChannel(client, payload) {
  if (!config.logChannelId || !client) return;
  try {
    const ch = await client.channels.fetch(config.logChannelId).catch(() => null);
    if (ch && ch.isTextBased && ch.isTextBased()) {
      if (typeof payload === "string") {
        await ch.send({ content: payload });
      } else if (typeof payload === "object") {
        await ch.send(payload);
      }
    }
  } catch (e) {
    console.error("❌ Log channel send error:", e);
  }
}

/**
 * unified function — ترسل إلى الويبهوك أو القناة حسب الإعدادات
 */
export async function sendLog(client, payload) {
  try {
    await sendLogToWebhook(payload);
  } catch (_) {}
  try {
    await sendLogToChannel(client, payload);
  } catch (_) {}
}
