import '../config.js';
import sequelize from '../database.js';
import jwt from 'jsonwebtoken';
import User from '../models/User.js';
import UserToken from '../models/UserToken.js';

(async () => {
  try {
    await sequelize.authenticate();
    console.log('[create-token] DB connected');
    const email = process.env.TEST_TOKEN_EMAIL || 'tournamentmanager@test.de';
    const user = await User.findOne({ where: { email } });
    if (!user) {
      console.error('[create-token] User not found:', email);
      process.exit(2);
    }
    const payload = { userId: user.id };
    const token = jwt.sign(payload, process.env.JWT_SECRET, { expiresIn: '7d' });
    const expiresAt = new Date(Date.now() + 7 * 24 * 3600 * 1000);
    await UserToken.create({ userId: user.id, token, expiresAt });
    console.log('[create-token] TOKEN_START');
    console.log(token);
    console.log('[create-token] TOKEN_END');
    process.exit(0);
  } catch (err) {
    console.error('[create-token] Error:', err);
    process.exit(3);
  }
})();
