// auth.js
const express = require('express');
const axios = require('axios');
const { log } = require('./logger');
const { saveToken } = require('./tokenStore');
const { createFulfillmentService } = require('./fulfillmentService');


const router = express.Router();

// replace these with environment vars or config
const CLIENT_ID = process.env.SHOPIFY_CLIENT_ID;
const CLIENT_SECRET = process.env.SHOPIFY_CLIENT_SECRET;

router.get('/auth/callback', async (req, res) => {
  const { shop, code } = req.query;
  if (!shop || !code) {
    log('general', `⚠️ Missing shop or code in callback: ${JSON.stringify(req.query)}`);
    return res.status(400).send('Missing shop or code parameter.');
  }

  log(shop, `🔔 Received OAuth callback (code=${code})`);

  try {
    log(shop, '🚀 Exchanging code for access token');
    const resp = await axios.post(
      `https://${shop}/admin/oauth/access_token`,
      { client_id: CLIENT_ID, client_secret: CLIENT_SECRET, code },
      { headers: { 'Content-Type': 'application/json' } }
    );

    const { access_token, scope } = resp.data;
    log(shop, `✅ Token received (scopes=${scope})`);
    saveToken(shop, access_token, scope);
    log(shop, '💾 Token saved to data/tokens.json');
    const { fulfillmentService } = await createFulfillmentService(shop, access_token);
    saveToken(shop, access_token, scope, fulfillmentService);
    console.log(`Fulfillment Service created neww: ${JSON.stringify(fulfillmentService)}`);
    log(shop, '✅ Fulfillment service created successfully');

    res.send('Access token saved. You may close this window.');
  } catch (err) {
    const errMsg = err.response?.data || err.message;
    log(shop, `❌ OAuth error: ${JSON.stringify(errMsg)}`);
    res.status(500).send('Failed to get access token');
  }
});

module.exports = router;
