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

exports.handler = async (event) => {
  const startedAt = new Date().toISOString();

  if (event.httpMethod === 'GET') {
    try {
      const { connectLambda } = require('@netlify/blobs');
      connectLambda(event);
      return {
        statusCode: 200,
        headers: { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' },
        body: JSON.stringify({ ok: true, function: 'save-config', mode: 'connection-test', dependency: '@netlify/blobs loaded', startedAt, finishedAt: new Date().toISOString() })
      };
    } catch (error) {
      return {
        statusCode: 500,
        headers: { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' },
        body: JSON.stringify({ ok: false, function: 'save-config', mode: 'connection-test', error: error.message, startedAt, finishedAt: new Date().toISOString() })
      };
    }
  }

  if (event.httpMethod !== 'POST') {
    return { statusCode: 405, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ok: false, error: 'Method not allowed', method: event.httpMethod }) };
  }

  let body;
  try {
    body = JSON.parse(event.body || '{}');
  } catch (error) {
    return { statusCode: 400, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ok: false, error: 'Invalid JSON', detail: error.message }) };
  }

  const requiredPin = process.env.ADMIN_PIN || '';
  if (requiredPin && body.pin !== requiredPin) {
    return { statusCode: 401, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ok: false, error: 'Incorrect admin PIN', pinRequired: true }) };
  }

  const config = {
    appName: String(body.appName || '').slice(0, 120),
    appLink: String(body.appLink || '').slice(0, 600),
    googleGroupLink: String(body.googleGroupLink || '').slice(0, 600),
    ownerEmail: String(body.ownerEmail || 'aaronstone.avr@gmail.com').slice(0, 240),
    appDescription: String(body.appDescription || '').slice(0, 2000),
    appImageData: String(body.appImageData || '').slice(0, 1800000),
    brandLogoData: String(body.brandLogoData || '').slice(0, 900000),
    updatedAt: new Date().toISOString()
  };

  try {
    const { connectLambda, getStore } = require('@netlify/blobs');
    connectLambda(event);
    const store = getStore({ name: STORE_NAME, consistency: 'eventual' });
    await store.setJSON(CONFIG_KEY, config);
    const saved = config;

    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: 'save-config',
        source: 'blob',
        store: STORE_NAME,
        key: CONFIG_KEY,
        startedAt,
        finishedAt: new Date().toISOString(),
        savedName: saved && saved.appName,
        savedUpdatedAt: saved && saved.updatedAt,
        note: 'Saved to Netlify Blobs using eventual consistency. Public page may take a short time to reflect changes.',
        config: saved || config
      })
    };
  } catch (error) {
    console.error('SAVE_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: 'save-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')
      })
    };
  }
};
