import { db } from '../src/db/client.js';
import { clearSharedResourceTokenFromRequests } from '../src/services/chat-room-service.js';
import { isLegacyChatShareTokenRowNeedingMigration } from '../src/services/shared-resource-token-service.js';

const TOKENS_TABLE = 'shared_resource_tokens';
const ACTIVITIES_TABLE = 'shared_resource_token_activities';
const ACCESS_PIN_SESSIONS_TABLE = 'shared_resource_access_pin_sessions';

async function main() {
  const rows = await db(TOKENS_TABLE)
    .select(
      'id',
      'name',
      'resource_type',
      'token_setting_id',
      'token_setting_snapshot_json',
      'resource_context_json',
      'allowed_app_ids_json',
      'share_path',
      'deleted_at',
      'created_at',
    )
    .where({ resource_type: 'chat-share' });

  const legacyRows = rows.filter((row) => isLegacyChatShareTokenRowNeedingMigration(row));
  const tokenIds = legacyRows.map((row) => String(row.id ?? '').trim()).filter(Boolean);

  if (tokenIds.length === 0) {
    console.log(JSON.stringify({ ok: true, deletedCount: 0, tokenIds: [] }, null, 2));
    await db.destroy();
    return;
  }

  await db.transaction(async (trx) => {
    for (const tokenId of tokenIds) {
      await clearSharedResourceTokenFromRequests(tokenId, trx);
    }

        const sharePaths = legacyRows.map((row) => String(row.share_path ?? '').trim()).filter(Boolean);
    if (sharePaths.length > 0) {
      await trx(ACCESS_PIN_SESSIONS_TABLE).whereIn('share_path', sharePaths).delete();
    }
    await trx(ACTIVITIES_TABLE).whereIn('token_id', tokenIds).delete();
    await trx(TOKENS_TABLE).whereIn('id', tokenIds).delete();
  });

  console.log(JSON.stringify({
    ok: true,
    deletedCount: tokenIds.length,
    tokenIds,
    names: legacyRows.map((row) => ({
      id: String(row.id ?? '').trim(),
      name: String(row.name ?? '').trim(),
      createdAt: row.created_at ?? null,
      deletedAt: row.deleted_at ?? null,
    })),
  }, null, 2));

  await db.destroy();
}

main().catch(async (error) => {
  console.error(error);
  await db.destroy();
  process.exitCode = 1;
});
