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

(async () => {
  const pool = new Pool({ connectionString: process.env.LOCAL_DB_URL });
  const client = await pool.connect();
  try {
    const duplicates = await client.query(`
      SELECT
        public.id AS public_id,
        public.user_id AS public_user_id,
        private.id AS private_id,
        private.user_id AS private_user_id,
        p.email,
        p.nickname,
        public.result_url AS public_url,
        private.result_url AS private_url,
        LEFT(COALESCE(public.prompt, ''), 80) AS prompt_preview
      FROM works public
      JOIN works private
        ON private.id <> public.id
       AND private.user_id <> '00000000-0000-0000-0000-000000000000'
       AND (
         private.result_url = public.result_url
         OR private.thumbnail_url = public.thumbnail_url
         OR (
           COALESCE(private.prompt, '') = COALESCE(public.prompt, '')
           AND private.created_at BETWEEN public.created_at - INTERVAL '10 minutes' AND public.created_at + INTERVAL '10 minutes'
         )
       )
      JOIN profiles p ON p.id = private.user_id
      WHERE public.is_public = true
        AND public.status = 'completed'
        AND public.user_id = '00000000-0000-0000-0000-000000000000'
      LIMIT 50
    `);

    const paramKeys = await client.query(`
      SELECT id, params
      FROM works
      WHERE is_public = true
        AND status = 'completed'
        AND user_id = '00000000-0000-0000-0000-000000000000'
      LIMIT 10
    `);

    console.log(JSON.stringify({
      duplicateCandidateCount: duplicates.rowCount,
      duplicateCandidates: duplicates.rows,
      paramSamples: paramKeys.rows,
    }, null, 2));
  } finally {
    client.release();
    await pool.end();
  }
})().catch((error) => {
  console.error(error);
  process.exit(1);
});
