import PocketBase from 'pocketbase';
import fs from 'fs';
import path from 'path';
import matter from 'gray-matter';

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;

interface PostFrontmatter {
  title: string;
  description: string;
  author: string;
  category: string;
  categoryColor: string;
  date: string;
  readTime: string;
  imageUrl: string;
  draft: boolean;
}

async function migrate() {
  console.log('🔄 Миграция постов в PocketBase...\n');

  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('❌ Ошибка авторизации в PocketBase');
    process.exit(1);
  }

  const blogDir = path.join(process.cwd(), 'frontend/src/content/blog');
  const files = fs.readdirSync(blogDir).filter(f => f.endsWith('.mdx'));

  console.log(`📂 Найдено ${files.length} постов в ${blogDir}\n`);

  let migrated = 0;
  let skipped = 0;

  for (const file of files) {
    const filePath = path.join(blogDir, file);
    const fileContent = fs.readFileSync(filePath, 'utf-8');
    const { data, content } = matter(fileContent);

    const frontmatter = data as PostFrontmatter;
    const slug = file.replace('.mdx', '');

    try {
      const record = await pb.collection('posts').create({
        title: frontmatter.title,
        description: frontmatter.description,
        author: frontmatter.author,
        category: frontmatter.category,
        categoryColor: frontmatter.categoryColor,
        date: frontmatter.date,
        readTime: frontmatter.readTime,
        imageUrl: frontmatter.imageUrl,
        slug: slug,
        draft: frontmatter.draft ?? false,
        content: content,
      });

      console.log(`✅ Мигрирован: ${slug}`);
      migrated++;
    } catch (e: any) {
      console.error(`❌ Ошибка миграции ${slug}:`, e.response?.data || e.message);
    }
  }

  console.log(`\n📊 Готово! Мигрировано: ${migrated}, пропущено: ${skipped}`);
}

migrate().catch(console.error);