import client, { ensureAuthenticated } from '../lib/directus';
import { readUsers, updateUser } from '@directus/sdk';
import { config } from '../lib/config';

async function fixToken() {
  console.log('🔑 Ensuring Directus Admin Token is set...');

  try {
    // 1. Authenticate with credentials
    await ensureAuthenticated();

    // 2. Find admin user
    const users = await client.request(
      readUsers({
        filter: {
          email: { _eq: config.directus.adminEmail },
        },
      }),
    );

    if (!users || users.length === 0) {
      console.error(`❌ Could not find user with email ${config.directus.adminEmail}`);
      process.exit(1);
    }

    const admin = users[0];
    const targetToken = config.directus.token;

    if (!targetToken) {
      console.error('❌ No DIRECTUS_API_TOKEN configured in environment.');
      process.exit(1);
    }

    if (admin.token === targetToken) {
      console.log('✅ Token is already correctly set.');
      return;
    }

    // 3. Update token
    console.log(`📡 Updating token for ${config.directus.adminEmail}...`);
    await client.request(
      updateUser(admin.id, {
        token: targetToken,
      }),
    );

    console.log('✨ Token successfully updated!');
  } catch (error: any) {
    console.error('❌ Error fixing token:');
    if (error.errors) {
      console.error(JSON.stringify(error.errors, null, 2));
    } else {
      console.error(error.message || error);
    }
    process.exit(1);
  }
}

fixToken();
