const DROPBOX_APP_KEY = process.env.DROPBOX_APP_KEY;
const DROPBOX_APP_SECRET = process.env.DROPBOX_APP_SECRET;
const DROPBOX_REFRESH_TOKEN = process.env.DROPBOX_REFRESH_TOKEN;

async function getAccessToken() {
  const response = await fetch('https://api.dropboxapi.com/oauth2/token', {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: new URLSearchParams({
      grant_type: 'refresh_token',
      refresh_token: DROPBOX_REFRESH_TOKEN,
      client_id: DROPBOX_APP_KEY,
      client_secret: DROPBOX_APP_SECRET,
    })
  });
  const data = await response.json();
  if (!data.access_token) {
    throw new Error('Failed to get access token: ' + JSON.stringify(data));
  }
  return data.access_token;
}

export default async function handler(req, res) {
  let accessToken;
  try {
    accessToken = await getAccessToken();
  } catch (err) {
    console.error('Token refresh error:', err);
    return res.status(500).json({ error: err.message });
  }

  if (req.method === 'GET' && req.query.info === '1') {
    try {
      const fileInfo = await fetch('https://api.dropboxapi.com/2/files/get_metadata', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${accessToken}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ path: '/CRAZE GmbH/Sales Reports/Data Matrix.xlsx' })
      });
      const data = await fileInfo.json();
      return res.json({ rev: data.rev, size: data.size, server_modified: data.server_modified });
    } catch (err) {
      return res.status(500).json({ error: err.message });
    }
  }

  try {
    const upstream = await fetch('https://content.dropboxapi.com/2/files/download', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${accessToken}`,
        'Dropbox-API-Arg': JSON.stringify({ path: '/CRAZE GmbH/Sales Reports/Data Matrix.xlsx' })
      }
    });

    if (!upstream.ok) {
      const errText = await upstream.text();
      console.error('Dropbox API error:', upstream.status, errText);
      return res.status(upstream.status).send('Dropbox error: ' + errText);
    }

    const buffer = await upstream.arrayBuffer();
    res.setHeader('Content-Type', 'application/octet-stream');
    res.setHeader('Cache-Control', 'no-store');
    res.send(Buffer.from(buffer));
  } catch (err) {
    console.error('Dropbox proxy error:', err);
    res.status(500).send('Proxy error: ' + err.message);
  }
}
