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

const SYSTEM_USER_ID = '00000000-0000-0000-0000-000000000000';

(async () => {
  const pool = new Pool({ connectionString: process.env.LOCAL_DB_URL });
  const client = await pool.connect();
  try {
    await client.query('BEGIN');
    const result = await client.query(`
      WITH candidates AS (
        SELECT DISTINCT ON (public.id)
          public.id AS public_id,
          private.user_id AS owner_user_id,
          CASE
            WHEN private.result_url = public.result_url THEN 1
            WHEN private.thumbnail_url = public.thumbnail_url THEN 2
            ELSE 3
          END AS confidence_rank,
          ABS(EXTRACT(EPOCH FROM (private.created_at - public.created_at))) AS time_distance
        FROM works public
        JOIN works private
          ON private.id <> public.id
         AND private.user_id <> $1
         AND (
           private.result_url = public.result_url
           OR (
             public.thumbnail_url IS NOT NULL
             AND 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 = $1
        ORDER BY public.id, confidence_rank, time_distance
      ),
      updated AS (
        UPDATE works w
        SET user_id = candidates.owner_user_id
        FROM candidates
        WHERE w.id = candidates.public_id
        RETURNING w.id, w.user_id
      )
      SELECT COUNT(*)::int AS fixed_count FROM updated
    `, [SYSTEM_USER_ID]);
    await client.query('COMMIT');
    console.log(JSON.stringify(result.rows[0] || { fixed_count: 0 }, null, 2));
  } catch (error) {
    await client.query('ROLLBACK');
    throw error;
  } finally {
    client.release();
    await pool.end();
  }
})().catch((error) => {
  console.error(error);
  process.exit(1);
});
