/**
 * Bing Webmaster Tools Integration
 * -----------------------------------
 * Auth: API key
 * API: https://ssl.bing.com/webmaster/api.svc/json
 */

import type { IntegrationCredentials } from "@/lib/services/integration-credentials";
import { SyncService, SyncResult, apiCall } from "./types";

const API_BASE = "https://ssl.bing.com/webmaster/api.svc/json";

export const bingWebmaster: SyncService = {
  id: "bing",
  name: "Bing Webmaster Tools",

  async connect(brandId: string, creds?: IntegrationCredentials): Promise<SyncResult> {
    const apiKey = creds?.apiKey || process.env.BING_WEBMASTER_API_KEY;
    if (!apiKey) {
      return { success: false, message: "Bing Webmaster requires an API key. Get one from the Bing Webmaster portal." };
    }

    // Verify by listing sites
    const res = await apiCall(`${API_BASE}/GetUserSites?apikey=${apiKey}`);

    if (!res.ok) return { success: false, message: `Bing connection failed: ${res.error}` };

    return {
      success: true,
      message: "Bing Webmaster Tools connected.",
      credentials: { apiKey },
      data: res.data as Record<string, unknown>,
    };
  },

  async disconnect(): Promise<SyncResult> {
    return { success: true, message: "Bing Webmaster Tools disconnected." };
  },

  async sync(brandId: string, creds?: IntegrationCredentials): Promise<SyncResult> {
    const apiKey = creds?.apiKey || process.env.BING_WEBMASTER_API_KEY;
    if (!apiKey) {
      return { success: false, message: "No API key — reconnect Bing Webmaster." };
    }

    const siteUrl = creds?.siteUrl as string;
    if (!siteUrl) {
      return { success: false, message: "No site URL configured for Bing." };
    }

    // Fetch query stats
    const res = await apiCall(
      `${API_BASE}/GetQueryStats?apikey=${apiKey}&siteUrl=${encodeURIComponent(siteUrl)}`
    );

    if (!res.ok) {
      return { success: false, message: `Bing sync failed: ${res.error}` };
    }

    const data = res.data as unknown[];
    return {
      success: true,
      message: `Synced ${Array.isArray(data) ? data.length : 0} query stats from Bing.`,
      data: { queries: data },
    };
  },
};
