const express = require('express');
const bodyParser = require('body-parser');
const jwt = require('jsonwebtoken');
const multer = require('multer');

const app = express();
app.use(bodyParser.json());
const upload = multer();

app.post('/generate-token', upload.none(), async (req, res) => {
  const { iss, privateKey, keyId } = req.body;

  if (!iss || !keyId || !privateKey) {
    return res.status(400).json({ error: 'Missing required fields' });
  }
  const payload = { iss, aud: 'appstoreconnect-v1' };
  console.log(payload, privateKey, {
    algorithm: 'ES256',
    header: {
      alg: 'ES256',
      kid: keyId
    }
  })
  try {
    const token = jwt.sign(payload, privateKey, {
      algorithm: 'ES256',
      header: {
        alg: 'ES256',
        kid: keyId
      }, expiresIn: '15m'
    });
    console.log(token, 'token');
    res.json({ access_token: token });
  } catch (error) {
    console.error('Error generating token:', error);
    if (error.message) {
      const token = jwt.sign(payload, privateKey, {
        algorithm: 'ES256',
        header: {
          alg: 'ES256',
          kid: keyId
        }, expiresIn: '15m'
      });
      console.log(token, 'token');
      return res.json({ access_token: token });
    }
    // res.status(500).json({ error: 'Failed to generate token' });
  }
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});
