import axios from "axios";
import crypto from "crypto";

const DIDIT_API_KEY = process.env.DIDIT_API_KEY;
const DIDIT_KYB_WORKFLOW_ID = process.env.DIDIT_KYB_WORKFLOW_ID;
const DIDIT_KYB_CALLBACK_URL = process.env.DIDIT_KYB_CALLBACK_URL || `${process.env.APP_URL || 'https://saasstagingairpero.airpero.com'}/merchant/kyb/return`;
const BASE_URL = "https://verification.didit.me/v3";

class DiditService {
  /**
   * Create a KYB session
   * @param {string} merchantId
   * @returns {Promise<{sessionId: string, url: string, token: string}>}
   */
  static async createSession(merchantId) {
    if (!DIDIT_API_KEY || !DIDIT_KYB_WORKFLOW_ID) {
      throw new Error("Didit API credentials (DIDIT_API_KEY and DIDIT_KYB_WORKFLOW_ID) are not configured in environment variables.");
    }

    const payload = {
      workflow_id: DIDIT_KYB_WORKFLOW_ID,
      vendor_data: merchantId,
      callback: DIDIT_KYB_CALLBACK_URL,
      metadata: { merchantId }
    };

    try {
      const response = await axios.post(
        `${BASE_URL}/session/`,
        payload,
        {
          headers: {
            "x-api-key": DIDIT_API_KEY,
            "Content-Type": "application/json",
          },
        }
      );

      return {
        sessionId: response.data.session_id,
        url: response.data.url || response.data.session_url,
        session_url: response.data.session_url || response.data.url,
        token: response.data.session_token,
      };
    } catch (error) {
      console.error("❌ [Didit] Error creating session");
      console.error("   URL:", `${BASE_URL}/session/`);
      console.error("   Payload sent:", JSON.stringify(payload));
      console.error("   Response status:", error.response?.status);
      console.error("   Response data:", JSON.stringify(error.response?.data || {}));
      console.error("   Raw error message:", error.message);
      throw new Error("Failed to create KYB verification session.");
    }
  }

  /**
   * Get session decision payload
   * @param {string} sessionId 
   * @returns {Promise<any>}
   */
  static async getSessionDecision(sessionId) {
    try {
      const response = await axios.get(
        `${BASE_URL}/session/${sessionId}/decision/`,
        {
          headers: {
            "x-api-key": DIDIT_API_KEY,
          },
        }
      );
      return response.data;
    } catch (error) {
      console.error("❌ [Didit] Error fetching decision:", error.response?.data || error.message);
      throw new Error("Failed to fetch KYB session decision.");
    }
  }

  /**
   * Verify webhook signature (X-Signature-V2)
   * @param {string} signature 
   * @param {string} rawBody 
   * @returns {boolean}
   */
  static verifyWebhookSignature(signature, rawBody) {
    if (!signature) return false;
    
    try {
      // In production, Didit uses HMAC-SHA256 with the API Key or Webhook Secret.
      // Usually, it's the webhook secret if defined, else fallback to API key based on their docs.
      const secret = process.env.DIDIT_WEBHOOK_SECRET || DIDIT_API_KEY;
      const expectedSignature = crypto
        .createHmac("sha256", secret)
        .update(rawBody)
        .digest("hex");
        
      return signature === expectedSignature;
    } catch (error) {
      console.error("❌ [Didit] Error verifying signature:", error);
      return false;
    }
  }
}

export default DiditService;

