const { Pool } = require('pg');
require('dotenv').config({ path: '.env.local' });

const base = 'http://127.0.0.1:5000';
const marker = `codex-import-edge-${Date.now()}`;

(async () => {
  const profileRes = await fetch(`${base}/api/profile?email=admin@example.com`);
  const profileData = await profileRes.json();
  const adminId = profileData.profile && profileData.profile.id;
  if (!adminId) throw new Error('admin profile not found');
  const token = `token-admin-${adminId}-${Date.now()}`;

  const tinyPng = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==';
  const payload = {
    _meta: {
      version: 'edge',
      platform: 'miaojing',
      exported_at: new Date().toISOString(),
      tables: ['announcements', 'works'],
      counts: { announcements: 1, works: 1 },
    },
    data: {
      auth_users: [],
      profiles: [],
      announcements: [{
        id: `ann-${Date.now()}-legacy`,
        title: marker,
        content: 'legacy id compatibility check',
        type: 'info',
        is_active: false,
        created_at: new Date().toISOString(),
      }],
      works: [{
        id: `work-${Date.now()}-legacy`,
        user_id: adminId,
        type: 'text2img',
        title: marker,
        prompt: marker,
        result_url: tinyPng,
        thumbnail_url: tinyPng,
        params: { referenceImage: tinyPng },
        width: 1,
        height: 1,
        status: 'completed',
        is_public: false,
        likes_count: 0,
        created_at: new Date().toISOString(),
      }],
    },
  };

  const importRes = await fetch(`${base}/api/admin/data-import`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${token}`,
    },
    body: JSON.stringify(payload),
  });
  const importBody = await importRes.json();

  const pool = new Pool({ connectionString: process.env.LOCAL_DB_URL });
  const client = await pool.connect();
  try {
    const rows = await client.query(
      `SELECT id, result_url, thumbnail_url, params
       FROM works
       WHERE title = $1 OR prompt = $1
       ORDER BY created_at DESC
       LIMIT 1`,
      [marker],
    );
    console.log(JSON.stringify({
      status: importRes.status,
      details: importBody.details,
      savedWork: rows.rows[0] || null,
    }, null, 2));

    await client.query('DELETE FROM works WHERE title = $1 OR prompt = $1', [marker]);
    await client.query('DELETE FROM announcements WHERE title = $1', [marker]);
  } finally {
    client.release();
    await pool.end();
  }
})().catch((error) => {
  console.error(error);
  process.exit(1);
});
