import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/db/client';

export const dynamic = 'force-dynamic';

export async function GET(req: NextRequest) {
  try {
    const { searchParams } = new URL(req.url);
    const limit = Math.max(1, parseInt(searchParams.get('limit') || '50'));

    const dbLogs = await db.getStoreActivityLogs(undefined, limit).catch(() => []);

    let unified = dbLogs.map((l: any) => ({
      id: l.id,
      shop_id: l.shop_id,
      shopify_domain: l.shopify_domain,
      shop_name: (l.shopify_domain || '').replace('.myshopify.com', ''),
      action: l.action,
      actor: l.actor || 'system',
      description: l.description || l.action,
      created_at: l.created_at || new Date().toISOString(),
      is_demo: false,
    }));

    // If database logs table has no custom actions yet, generate baseline initial logs from real shops
    if (unified.length === 0) {
      const allShops = await db.getAllShops().catch(() => []);
      for (const s of allShops) {
        unified.push({
          id: `act_${s.id}_installed`,
          shop_id: s.id,
          shopify_domain: s.shopify_domain,
          shop_name: s.shop_name || s.shopify_domain.replace('.myshopify.com', ''),
          action: 'app_installed',
          actor: 'merchant',
          description: `Store installed Meta Commerce Connector on ${s.shopify_domain}`,
          created_at: s.installed_at || s.created_at || new Date().toISOString(),
          is_demo: false,
        });
      }
    }

    unified.sort((a: any, b: any) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime());

    return NextResponse.json({
      success: true,
      logs: unified.slice(0, limit),
    });
  } catch (err: any) {
    return NextResponse.json(
      { success: false, error: err?.message || 'Failed to fetch activity logs' },
      { status: 500 }
    );
  }
}
