import Surreal from 'surrealdb';

const db = new Surreal();

async function main() {
  try {
    await db.connect(
      process.env.SURREAL_URL ||
        'wss://gentle-island-06di2pv2c9po3a8euttd1alkek.aws-euw1.surreal.cloud/rpc'
    );
    await db.signin({
      username: process.env.SURREAL_USER || 'rootuser',
      password: process.env.SURREAL_PASS || 'n1n@S1mone',
    });
    await db.use({
      namespace: process.env.SURREAL_NAMESPACE || 'neoad',
      database: process.env.SURREAL_DATABASE || 'neodb',
    });

    console.log('✅ Connecté à SurrealDB Cloud');

    const queries = `
      DEFINE FIELD OVERWRITE in_production ON template TYPE bool DEFAULT false;
      DEFINE FIELD OVERWRITE display_order ON template TYPE option<int>;
      DEFINE FIELD OVERWRITE duration_seconds ON template TYPE option<int>;
      DEFINE FIELD OVERWRITE format ON template TYPE option<string>;
      DEFINE FIELD OVERWRITE price ON template TYPE option<number>;
      DEFINE FIELD OVERWRITE plainly_template_id ON template TYPE option<string>;
      DEFINE FIELD OVERWRITE thumbnail_url ON template TYPE option<string>;
    `;

    console.log('📝 Application des champs optionnels sur template...');
    await db.query(queries);
    console.log('✅ Champs mis à jour');

    const [templates] = await db.query<[any[]]>(
      `SELECT id, name, in_production, plainly_template_id FROM template ORDER BY name`
    );

    console.log('\n📋 État des templates (production/disponible):');
    console.log('─'.repeat(70));
    for (const t of templates || []) {
      const status = t.in_production ? '✓ Disponible' : '○ Bientôt (grisé)';
      const plain = t.plainly_template_id ? `Plainly: ${t.plainly_template_id}` : 'Plainly: —';
      console.log(`${t.name.padEnd(40)} ${status} | ${plain}`);
    }
    console.log('─'.repeat(70));
    console.log(`Total: ${templates?.length || 0}`);

    await db.close();
  } catch (err) {
    console.error('❌ Erreur migration template nullable:', err);
    process.exit(1);
  }
}

main();
