// pages/api/auth/apple-token.js
import jwt from 'jsonwebtoken';
import fs from 'fs';
import path from 'path';
const dotenv = require("dotenv");


export default async function handler(req, res) {
    if (req.method === 'GET') {
        try {
            const appleKey = fs.readFileSync(path.resolve('./_deploy/appleKey.p8'), 'utf8');
            const teamID = process.env.APPLE_TEAM_ID || "XC57P9SXDK";
            const keyID = process.env.APPLE_KEY_ID || "TB3V355G5Y";
            const appleAppID = process.env.APPLE_APP_ID || "com.mwitnessing.mwitnessing";
            const token = jwt.sign({}, appleKey, {
                algorithm: 'ES256',
                expiresIn: '180d',
                issuer: teamID,
                header: {
                    alg: 'ES256',
                    kid: keyID,
                },
                audience: 'https://appleid.apple.com',
                subject: appleAppID,
            });

            // Redirect to Apple's authentication page, or send the token to the client to do so
            console.log(token);
            res.status(200).send({
                message: 'Generated token for Apple Sign In',
                token: token
            });
        } catch (error) {
            console.error('Error signing in with Apple:', error);
            res.status(500).send({ error: 'Failed to sign in with Apple' });
        }
    } else {
        // Handle any non-GET requests
        res.setHeader('Allow', ['GET']);
        res.status(405).end(`Method ${req.method} Not Allowed`);
    }
}
