import dayjs from "dayjs";
import { prisma } from "../lib/prisma";
import { RankingService } from "./services/ranking.service";
import { NaverRealEstate } from "./services/naver.service";
import { realestateTypes, realtorIds } from "./config";

async function getRanking(articles: RealEstateArticle[], checkDate: Date) {
  const { token, cookie } = await this.naver.getRankingToken();

  const limit = pLimit(20);
  const tasks = articles.map((article) => {
    return limit(async () => {
      try {
        // cortarNo, lgeo 확인
        if (!article.cortarNo || !article.lgeo) {
          const { cortarNo, lgeo } = await this.updateCortarNoAndLgeo(article);
          article.cortarNo = cortarNo;
          article.lgeo = lgeo;
        }

        // 랭킹 조회 및 업데이트
        const ranking = await this.naver.getRanking(article, token, cookie);
        await prisma.realEstateArticle.update({
          where: { id: article.id },
          data: {
            ranking,
            rankCheckDate: checkDate.toISOString(),
          },
        });

        console.log(
          `✅ ${article.articleNumber} - 랭킹 업데이트 완료: ${ranking}위`
        );
      } catch (error) {
        console.error(`❌ updateRanking 오류:`, error);
      }
    });
  });
  console.log("🔹 예약된 작업 수:", tasks.length);
  const results = await Promise.allSettled(tasks);
  console.log("🟢 모든 limit 작업 완료:", results.length);
  await Bun.sleep(100);
}

(async () => {
  const articleNo = process.argv[2];
  console.log(articleNo);
  process.exit();
  const ranking = getRanking();
})();
