import { NextResponse } from 'next/server';

// Instagram Graph API integration
// This fetches the latest posts from the connected Instagram Business/Creator account
// The access token is stored in the environment variable INSTAGRAM_ACCESS_TOKEN

const INSTAGRAM_ACCESS_TOKEN = process.env.INSTAGRAM_ACCESS_TOKEN || '';
const CACHE_DURATION = 600; // Cache for 10 minutes (in seconds)

let cachedData: any = null;
let cacheTimestamp = 0;

export async function GET() {
 try {
  // Return cached data if still fresh
  const now = Date.now();
  if (cachedData && (now - cacheTimestamp) < CACHE_DURATION * 1000) {
   return NextResponse.json(cachedData);
  }

  if (!INSTAGRAM_ACCESS_TOKEN) {
   // Return placeholder data when no token is configured
   return NextResponse.json({
    posts: [
     {
      id: 'placeholder-1',
      media_url: 'https://images.pexels.com/photos/440731/pexels-photo-440731.jpeg?auto=compress&cs=tinysrgb&w=800',
      permalink: 'https://instagram.com',
      caption: 'Exclusive look at our new 5-acre agricultural plot just outside the city. Perfect for farming or investment! 🌱✨ #RealEstate #LandForSale',
      media_type: 'VIDEO',
      thumbnail_url: 'https://images.pexels.com/photos/440731/pexels-photo-440731.jpeg?auto=compress&cs=tinysrgb&w=800',
      timestamp: new Date().toISOString(),
     },
     {
      id: 'placeholder-2',
      media_url: 'https://images.pexels.com/photos/259280/pexels-photo-259280.jpeg?auto=compress&cs=tinysrgb&w=800',
      permalink: 'https://instagram.com',
      caption: 'Premium 10-acre plot with mountain views! Drone walkthrough of our latest verified listing 🏡🌿 #FarmLand #Investment',
      media_type: 'VIDEO',
      thumbnail_url: 'https://images.pexels.com/photos/259280/pexels-photo-259280.jpeg?auto=compress&cs=tinysrgb&w=800',
      timestamp: new Date().toISOString(),
     },
     {
      id: 'placeholder-3',
      media_url: 'https://images.pexels.com/photos/461960/pexels-photo-461960.jpeg?auto=compress&cs=tinysrgb&w=800',
      permalink: 'https://instagram.com',
      caption: 'Road-facing agricultural land near highway. Site visit reel! 🚜🌾 #ZameenProperties #LandDeals',
      media_type: 'VIDEO',
      thumbnail_url: 'https://images.pexels.com/photos/461960/pexels-photo-461960.jpeg?auto=compress&cs=tinysrgb&w=800',
      timestamp: new Date().toISOString(),
     },
    ],
    isPlaceholder: true,
   });
  }

  // Fetch latest media from Instagram Graph API
  const response = await fetch(
   `https://graph.instagram.com/me/media?fields=id,caption,media_type,media_url,thumbnail_url,permalink,timestamp&limit=6&access_token=${INSTAGRAM_ACCESS_TOKEN}`,
   { next: { revalidate: CACHE_DURATION } }
  );

  if (!response.ok) {
   throw new Error(`Instagram API error: ${response.status}`);
  }

  const data = await response.json();
  
  // Filter to only VIDEO (reels) and IMAGE types, prioritize videos
  const posts = (data.data || [])
   .filter((post: any) => post.media_type === 'VIDEO' || post.media_type === 'IMAGE' || post.media_type === 'CAROUSEL_ALBUM')
   .slice(0, 6)
   .map((post: any) => ({
    id: post.id,
    media_url: post.media_url,
    permalink: post.permalink,
    caption: post.caption || '',
    media_type: post.media_type,
    thumbnail_url: post.thumbnail_url || post.media_url,
    timestamp: post.timestamp,
   }));

  const result = { posts, isPlaceholder: false };
  
  // Update cache
  cachedData = result;
  cacheTimestamp = now;

  return NextResponse.json(result);
 } catch (error) {
  console.error('Instagram API Error:', error);
  // Return placeholder on error
  return NextResponse.json({
   posts: [],
   isPlaceholder: true,
   error: 'Failed to fetch Instagram posts',
  });
 }
}
