const router = require('express').Router();
const { createClient } = require('@supabase/supabase-js');
const { getSupabaseUrl, getSupabaseKey, getSupabaseServiceKey } = require('./get-constants');

let supabase = null;

async function initSupabaseClient() {
  const supabaseUrl = await getSupabaseUrl();
  const supabaseAnonKey = await getSupabaseKey();
  const supabaseServiceRoleKey = await getSupabaseServiceKey();
  supabase = createClient(supabaseUrl, supabaseServiceRoleKey);
}

function getSupabaseClient() {
  if (!supabase) {
    throw new Error('Supabase client is not initialized. Call initSupabaseClient first.');
  }
  return supabase;
}

// POST /refresh-supabase-client
router.post('/refresh-supabase-client', async (req, res) => {
try {
    await initSupabaseClient();
    res.json({ success: true, message: 'Supabase client refreshed' });
} catch (error) {
    res.status(500).json({ error: error.message });
}
});

// Инициализация клиента при старте
(async () => {
    await initSupabaseClient();
})();

module.exports = {
  getSupabaseClient,
  supabaseRouter: router
};