const STORE_NAME = 'nexus-app-test-page';
const CONFIG_KEY = 'app-config';

exports.handler = async (event) => {
  const startedAt = new Date().toISOString();
  try {
    const { connectLambda, getStore } = require('@netlify/blobs');
    connectLambda(event);
    const store = getStore({ name: STORE_NAME, consistency: 'eventual' });
    const data = await store.get(CONFIG_KEY, { type: 'json' });

    return {
      statusCode: 200,
      headers: {
        'Content-Type': 'application/json',
        'Cache-Control': 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0',
        'Pragma': 'no-cache',
        'Expires': '0'
      },
      body: JSON.stringify({
        ok: true,
        function: 'get-config',
        source: data ? 'blob' : 'default-empty',
        store: STORE_NAME,
        key: CONFIG_KEY,
        startedAt,
        finishedAt: new Date().toISOString(),
        config: data || {}
      })
    };
  } catch (error) {
    console.error('GET_CONFIG_FAILED', error);
    return {
      statusCode: 500,
      headers: {
        'Content-Type': 'application/json',
        'Cache-Control': 'no-store, no-cache, must-revalidate, max-age=0'
      },
      body: JSON.stringify({
        ok: false,
        function: 'get-config',
        source: 'error',
        store: STORE_NAME,
        key: CONFIG_KEY,
        startedAt,
        finishedAt: new Date().toISOString(),
        error: error.message,
        stack: String(error.stack || '').split('\n').slice(0, 4).join('\n')
      })
    };
  }
};
