/**
 * Directus Client Configuration
 * Provides a configured Directus SDK client for interacting with the Directus API
 */

const { createDirectus, rest, authentication } = require('@directus/sdk');
const dotenv = require('dotenv');
const path = require('path');

// Load environment variables from project root
dotenv.config({ path: path.resolve(__dirname, '../../.env') });

// Directus configuration from environment or defaults
const DIRECTUS_CONFIG = {
  url: process.env.DIRECTUS_URL || 'https://enias.zeabur.app',
  token: process.env.DIRECTUS_TOKEN || '1frxUfw1TY_OUSHNPmQWDAeAAU0l2kxu',
  email: process.env.DIRECTUS_EMAIL,
  password: process.env.DIRECTUS_PASSWORD
};

/**
 * Create and configure Directus client
 * @returns {Object} Configured Directus client instance
 */
function createDirectusClient() {
  const client = createDirectus(DIRECTUS_CONFIG.url)
    .with(rest())
    .with(authentication());

  // Add authentication method
  client.authenticate = async () => {
    if (DIRECTUS_CONFIG.token) {
      // Use static token
      await client.setToken(DIRECTUS_CONFIG.token);
      console.log('✅ Authenticated with static token');
    } else if (DIRECTUS_CONFIG.email && DIRECTUS_CONFIG.password) {
      // Use email/password authentication
      await client.login(DIRECTUS_CONFIG.email, DIRECTUS_CONFIG.password);
      console.log('✅ Authenticated with email/password');
    } else {
      throw new Error('No authentication credentials provided. Set DIRECTUS_TOKEN or DIRECTUS_EMAIL/DIRECTUS_PASSWORD');
    }
  };

  return client;
}

/**
 * Get authenticated Directus client
 * @returns {Promise<Object>} Authenticated Directus client
 */
async function getAuthenticatedClient() {
  const client = createDirectusClient();
  await client.authenticate();
  return client;
}

/**
 * Test connection to Directus
 * @returns {Promise<boolean>} True if connection successful
 */
async function testConnection() {
  try {
    const client = await getAuthenticatedClient();
    // Use readMe from SDK
    const { readMe } = require('@directus/sdk');
    const response = await client.request(readMe());
    console.log('✅ Connected to Directus as:', response.email || 'API User');
    return true;
  } catch (error) {
    console.error('❌ Failed to connect to Directus:', error.message);
    return false;
  }
}

module.exports = {
  createDirectusClient,
  getAuthenticatedClient,
  testConnection,
  DIRECTUS_CONFIG
};