import { withAdmin } from '../../../lib/permission-middleware';
import { checkImportRateLimit } from '../../../lib/rate-limit.js';
import {
  runCatalogSync,
  runUnifiedCatalogSync,
} from '../../../lib/card-import/sync-catalog.js';
import { runBulkMtgSync } from '../../../lib/card-import/bulk-sync.js';

export default withAdmin(async function handler(req, res, user) {
  if (req.method !== 'POST') {
    return res.status(405).json({ error: 'Method not allowed' });
  }

  const { allowed, reset } = await checkImportRateLimit(req, user.userId);
  if (!allowed) {
    res.setHeader('Retry-After', Math.ceil((reset - Date.now()) / 1000));
    return res.status(429).json({ error: 'Too many attempts. Try again later.' });
  }

  const mode = req.body?.mode || 'unified';

  try {
    if (mode === 'bulk') {
      const summary = await runBulkMtgSync();
      return res.status(200).json({ success: true, ...summary });
    }

    if (mode === 'unified') {
      const summary = await runUnifiedCatalogSync();
      return res.status(200).json({ success: true, ...summary });
    }

    const summary = await runCatalogSync();
    return res.status(200).json({ success: true, ...summary });
  } catch (error) {
    console.error('[POST /api/admin/sync-catalog]', error);
    return res.status(500).json({ error: 'Catalog sync failed', details: error.message });
  }
});
