import { redisConnection } from "$connections/index.js";
import { servicesConfig } from "$config/index.js";
import { sejamClient } from "$clients/index.js";

const SEJAM_ACCESS_TOKEN_KEY = "sejam:access_token";
const SEJAM_ACCESS_TOKEN_TTL = 5 * 60; // 5 minutes

export const getAccessToken = async () => {
  try {
    // Try to get cached token from Redis
    const cachedToken = await redisConnection.get(SEJAM_ACCESS_TOKEN_KEY);
    if (cachedToken) {
      console.log("✅ Using cached SEJAM access token");
      return cachedToken;
    }

    // Fetch new token from SEJAM
    console.log("🔄 Fetching new SEJAM access token...");
    const response = await sejamClient.post(
      "/accessToken",
      {
        username: servicesConfig.sejamConfig.username,
        password: servicesConfig.sejamConfig.password,
      },
      {
        headers: {
          accept: "application/json",
          "Content-Type": "application/json-patch+json",
        },
      },
    );

    const { accessToken } = response?.data?.data;

    if (!accessToken) {
      throw new Error("No access token received from SEJAM");
    }

    // Cache token in Redis with TTL
    await redisConnection.setex(
      SEJAM_ACCESS_TOKEN_KEY,
      SEJAM_ACCESS_TOKEN_TTL,
      accessToken,
    );

    console.log("✅ New SEJAM access token Generated");
    return accessToken;
  } catch (error) {
    console.error("❌ Error getting SEJAM access token:", error.message);
    throw {
      status: 503,
      message: "خطا در اتصال به سرویس احراز هویت",
      details: error.response?.data || error.message,
    };
  }
};

export const requestOtp = async (identifier) => {
  try {
    const accessToken = await getAccessToken();

    await sejamClient.post(
      "/kycOtp",
      {
        uniqueIdentifier: identifier,
      },
      {
        headers: {
          "Content-Type": "application/json-patch+json",
          Authorization: `Bearer ${accessToken}`,
        },
      },
    );

    console.log(`✅ OTP sent to identifier: ${identifier}`);
    return true;
  } catch (error) {
    console.error("❌ Error requesting OTP:", error.message);

    // Handle specific SEJAM errors
    if (error.response?.status === 404) {
      throw {
        status: 404,
        message: "کد ملی در سیستم سجام یافت نشد",
      };
    }

    if (error.response?.status === 400) {
      throw {
        status: 400,
        message: "کد ملی نامعتبر است",
      };
    }

    throw {
      status: error.status || 503,
      message: error.message || "خطا در ارسال کد تایید",
      details: error.response?.data || error.message,
    };
  }
};

export const verifyOtpAndGetProfile = async (identifier, otp) => {
  try {
    const accessToken = await getAccessToken();

    const response = await sejamClient.get(
      `/servicesWithOtp/profiles/${identifier}`,
      {
        params: { otp },
        headers: {
          Accept: "application/json",
          Authorization: `Bearer ${accessToken}`,
        },
      },
    );

    if (!response.data?.data) {
      throw new Error("Invalid response from SEJAM");
    }

    console.log(`✅ Profile retrieved for identifier: ${identifier}`);
    return response.data;
  } catch (error) {
    console.error("❌ Error verifying OTP:", error.message);

    // Handle specific SEJAM errors
    if (error.response?.status === 401 || error.response?.status === 403) {
      throw {
        status: 401,
        message: "کد تایید نامعتبر است",
      };
    }

    if (error.response?.status === 404) {
      throw {
        status: 404,
        message: "کاربر یافت نشد",
      };
    }

    throw {
      status: error.status || 503,
      message: error.message || "خطا در تایید کد",
      details: error.response?.data || error.message,
    };
  }
};
