import { withAdmin } from '../../../lib/permission-middleware';
import { checkImportRateLimit } from '../../../lib/rate-limit.js';
import { importPokemonSet } from '../../../lib/card-import/pokemon.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.' });
  }

  try {
    const { setCode } = req.body;

    if (!setCode) {
      return res.status(400).json({ error: 'Set code is required' });
    }

    console.log(`Starting import for Pokemon set: ${setCode}`);
    const result = await importPokemonSet(setCode);
    console.log(
      `Import completed for set ${setCode}: ${result.imported} imported, ${result.skipped} skipped`
    );

    return res.status(200).json({
      success: true,
      message: `Import completed for set ${setCode}`,
      ...result,
    });
  } catch (error) {
    console.error('Card import error:', error);
    return res.status(500).json({
      error: 'Import failed',
      details: error.message,
    });
  }
});
