import PocketBase from 'pocketbase';

const PB_URL = process.env.POCKETBASE_URL || 'http://127.0.0.1:8090';
const ADMIN_EMAIL = process.env.PB_ADMIN_EMAIL;
const ADMIN_PASSWORD = process.env.PB_ADMIN_PASSWORD;

async function createCollection() {
  if (!ADMIN_EMAIL || !ADMIN_PASSWORD) {
    console.error('❌ Укажите PB_ADMIN_EMAIL и PB_ADMIN_PASSWORD в .env');
    process.exit(1);
  }

  const pb = new PocketBase(PB_URL);

  try {
    await pb.admins.authWithPassword(ADMIN_EMAIL, ADMIN_PASSWORD);
    console.log('✅ Подключено к PocketBase');
  } catch (e) {
    console.error('❌ Ошибка авторизации');
    process.exit(1);
  }

  try {
    const collection = await pb.collections.create({
      name: 'posts',
      type: 'base',
      system: false,
      schema: [
        { name: 'title', type: 'text', required: true },
        { name: 'description', type: 'text', required: true },
        { name: 'author', type: 'text', required: false },
        { name: 'category', type: 'text', required: false },
        { name: 'categoryColor', type: 'text', required: false },
        { name: 'date', type: 'date', required: true },
        { name: 'readTime', type: 'text', required: false },
        { name: 'imageUrl', type: 'text', required: false },
        { name: 'slug', type: 'text', required: true },
        { name: 'draft', type: 'bool', required: false },
        { name: 'content', type: 'editor', required: false },
      ],
      listRule: '',
      viewRule: '',
      createRule: '@request.auth.id != ""',
      updateRule: '@request.auth.id != ""',
      deleteRule: '@request.auth.id != ""',
    });

    console.log('✅ Коллекция "posts" создана');
    console.log('   ID:', collection.id);
  } catch (e: any) {
    if (e.data?.message?.includes('already exists')) {
      console.log('ℹ️  Коллекция "posts" уже существует');
    } else {
      console.error('❌ Ошибка:', e.data || e.message);
    }
  }
}

createCollection();