import axios from 'axios';

/**
 * Trigger on-demand cache revalidation on the Next.js frontend
 * @param {string} tag - The cache tag to revalidate
 */
export async function revalidateTag(tag: string) {
  const frontendUrl = process.env.FRONTEND_URL;
  const revalidationSecret = process.env.REVALIDATION_SECRET;
  const timestamp = new Date().toISOString();

  if (!frontendUrl || !revalidationSecret) {
    console.warn(
      `[${timestamp}] ⚠️  Skipping revalidation: FRONTEND_URL or REVALIDATION_SECRET not set in Strapi .env`
    );
    console.warn(
      `[${timestamp}]    Tag that would have been revalidated: ${tag}`
    );
    return;
  }

  try {
    const startTime = Date.now();
    console.log(
      `[${timestamp}] 🔄 Triggering revalidation for tag: "${tag}" → ${frontendUrl}`
    );

    const response = await axios.post(
      `${frontendUrl}/api/revalidate`,
      {
        tag,
        secret: revalidationSecret,
      },
      {
        timeout: 10000, // 10 second timeout
      }
    );

    const duration = Date.now() - startTime;

    if (response.data.revalidated) {
      console.log(
        `[${timestamp}] ✅ Successfully revalidated tag: "${tag}" (${duration}ms)`
      );
    } else {
      console.warn(
        `[${timestamp}] ⚠️  Revalidation response indicates failure for tag: "${tag}"`
      );
      console.warn(`[${timestamp}]    Response:`, response.data);
    }
  } catch (error: any) {
    const duration = error.response ? 'timed out' : 'failed';
    console.error(
      `[${timestamp}] ❌ Failed to trigger revalidation for tag: "${tag}" (${duration})`
    );

    if (error.response) {
      // Server responded with error status
      console.error(
        `[${timestamp}]    Status: ${error.response.status} ${error.response.statusText}`
      );
      console.error(`[${timestamp}]    Response:`, error.response.data);
    } else if (error.request) {
      // Request made but no response received
      console.error(
        `[${timestamp}]    No response from ${frontendUrl}/api/revalidate`
      );
      console.error(
        `[${timestamp}]    Check if Next.js server is running and accessible`
      );
    } else {
      // Error setting up request
      console.error(`[${timestamp}]    Error: ${error.message}`);
    }
  }
}

/**
 * Trigger on-demand path revalidation on the Next.js frontend
 * @param {string[]} paths - Paths to revalidate (e.g. ['/properties/residential/my-slug'])
 */
export async function revalidatePaths(paths: string[]) {
  const frontendUrl = process.env.FRONTEND_URL;
  const revalidationSecret = process.env.REVALIDATION_SECRET;
  const timestamp = new Date().toISOString();

  if (!frontendUrl || !revalidationSecret) {
    console.warn(
      `[${timestamp}] ⚠️  Skipping path revalidation: FRONTEND_URL or REVALIDATION_SECRET not set in Strapi .env`
    );
    return;
  }

  const validPaths = paths.filter((p) => typeof p === 'string' && p.length > 0);
  if (validPaths.length === 0) {
    console.warn(`[${timestamp}] ⚠️  No valid paths to revalidate`);
    return;
  }

  try {
    const startTime = Date.now();
    console.log(
      `[${timestamp}] 🔄 Triggering path revalidation (${validPaths.length} path(s)) → ${frontendUrl}`
    );

    const response = await axios.post(
      `${frontendUrl}/api/revalidate`,
      {
        paths: validPaths,
        secret: revalidationSecret,
      },
      {
        timeout: 10000,
      }
    );

    const duration = Date.now() - startTime;

    if (response.data.revalidated) {
      console.log(
        `[${timestamp}] ✅ Successfully revalidated paths (${duration}ms)`
      );
    } else {
      console.warn(`[${timestamp}] ⚠️  Path revalidation response:`, response.data);
    }
  } catch (error: any) {
    console.error(
      `[${timestamp}] ❌ Failed to trigger path revalidation:`,
      error.response?.data ?? error.message
    );
  }
}
