import axios, { type AxiosInstance } from "axios";
import axiosRetry from "axios-retry";
import type {
  ArticleItem,
  ArticleResponse,
  NaverRealEstateConfig,
} from "../types/naver.types";
import { prisma } from "../../lib/prisma";
import type { RealEstateArticle } from "../generated/prisma";
import { findNearest } from "geolib";
import http from "http";
import https from "https";

// axios 인스턴스 생성 및 retry 설정
const axiosInstance = axios.create({
  // httpAgent: new http.Agent({ keepAlive: false }),
  // httpsAgent: new https.Agent({ keepAlive: false }),
});
axiosRetry(axiosInstance, {
  retries: 4, // 4번 재시도
  retryDelay: (retryCount: number) => {
    console.log(`재시도 ${retryCount}번째 시도 중...`);
    return retryCount * 2000; // 2초, 4초, 6초, 8초 대기
  },
  retryCondition: (error: any) => {
    // 네트워크 에러 또는 5xx 에러일 때 재시도
    return true;
  },
});

export class NaverRealEstate {
  async getRankingToken() {
    try {
      const response = await axios.get("https://new.land.naver.com/houses", {
        adapter: "fetch",
        proxy: {
          host: "gw.dataimpulse.com",
          port: 823,
          auth: {
            username: "0bdeb90b7713c370cdeb__cr.kr",
            password: "a5ae50d6913bd778",
          },
        },
        params: {
          ms: "37.532448,127.0014059,19",
          a: "VL",
          b: "B2",
          e: "RETAIL",
        },
        headers: {
          connection: "close",
          accept:
            "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8",
          "accept-language": "ko;q=0.8",
          "cache-control": "no-cache",
          pragma: "no-cache",
          priority: "u=0, i",
          "sec-ch-ua":
            '"Brave";v="141", "Not?A_Brand";v="8", "Chromium";v="141"',
          "sec-ch-ua-mobile": "?0",
          "sec-ch-ua-platform": '"Windows"',
          "sec-fetch-dest": "document",
          "sec-fetch-mode": "navigate",
          "sec-fetch-site": "none",
          "sec-fetch-user": "?1",
          "sec-gpc": "1",
          "upgrade-insecure-requests": "1",
          "user-agent":
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36",
        },
      });

      const html = response.data;

      // HTML에서 rankingToken 추출
      const tokenMatch = html.match(/token["'\s:]+["']([^"']+)["']/);
      const rankingToken = tokenMatch ? tokenMatch[1] : null;
      if (!rankingToken) {
        throw new Error("rankingToken을 찾을 수 없습니다");
      }

      // 쿠키 추출
      const cookies = response.headers["set-cookie"];
      const cookieString = cookies
        ? cookies.map((cookie: string) => cookie.split(";")[0]).join("; ")
        : "";

      return {
        token: rankingToken,
        cookie: cookieString,
      };
    } catch (error) {
      console.error(`❌ 오류 발생:`, error);
      throw error;
    }
  }
  private realtorId: string;
  private seed: string | null;
  private client: AxiosInstance;
  private baseUrl: string;
  private tradeTypes: string[];
  private realestateTypes: string[];

  constructor(config: NaverRealEstateConfig) {
    this.realtorId = config.realtorId;
    this.seed = config.seed || null;
    this.baseUrl = config.baseUrl || "https://fin.land.naver.com";
    this.tradeTypes = config.tradeTypes || ["A1", "B1", "B2", "B3"];
    this.realestateTypes = config.realestateTypes || [
      "A01",
      "A02",
      "A06",
      "C01",
      "C02",
      "C03",
      "C04",
      "D01",
      "D02",
      "D03",
      "D04",
      "D05",
      "E01",
      "E03",
    ];

    this.client = axios.create({
      baseURL: this.baseUrl,
      headers: {
        "User-Agent":
          "Mozilla/5.0 (iPhone; CPU iPhone OS 18_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.5 Mobile/15E148 Safari/604.1",
        Accept: "application/json, text/plain, */*",
        "Content-Type": "application/json",
      },
    });
  }

  /**
   * Seed 값을 가져옵니다 (DB에 저장)
   */
  async fetchSeed(cookie: string): Promise<string> {
    try {
      let data = JSON.stringify({
        size: 30,
        realtorId: "namyeong00",
        userChannelType: "PC",
        tradeTypes: ["A1", "B1", "B2", "B3"],
        realestateTypes: [
          "A01",
          "A02",
          "A06",
          "C02",
          "C03",
          "C04",
          "D01",
          "D02",
          "D03",
          "D04",
          "D05",
          "E01",
          "E03",
        ],
        articleSortType: "RANKING_DESC",
        lastInfo: [],
      });
      let config = {
        method: "post",
        maxBodyLength: Infinity,
        url: "https://fin.land.naver.com/front-api/v1/realtor/articles",
        adapter: "fetch",
        proxy: {
          host: "gw.dataimpulse.com",
          port: 823,
          auth: {
            username: "0bdeb90b7713c370cdeb__cr.kr",
            password: "a5ae50d6913bd778",
          },
        },
        headers: {
          connection: "close",
          accept: "application/json, text/plain, */*",
          "accept-language": "ko;q=0.7",
          "cache-control": "no-cache",
          "content-type": "application/json",
          origin: "https://fin.land.naver.com",
          pragma: "no-cache",
          priority: "u=1, i",
          referer: "https://fin.land.naver.com/realtor/namyeong00",
          "sec-ch-ua":
            '"Brave";v="141", "Not?A_Brand";v="8", "Chromium";v="141"',
          "sec-ch-ua-mobile": "?0",
          "sec-ch-ua-platform": '"Windows"',
          "sec-fetch-dest": "empty",
          "sec-fetch-mode": "cors",
          "sec-fetch-site": "same-origin",
          "sec-gpc": "1",
          "user-agent":
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36",
          cookie: cookie,
        },
        data: data,
      };

      const response = await axios.request(config);

      // body 응답에서 seed 값 추출
      const seed = response.data?.result?.seed;

      if (!seed) {
        throw new Error("Seed 값을 찾을 수 없습니다");
      }

      const extractedSeed = seed;
      this.seed = extractedSeed;

      return extractedSeed;
    } catch (error) {
      throw new Error(`Seed 가져오기 실패: ${error}`);
    }
  }

  /**
   * 현재 저장된 Seed 값을 반환합니다
   */
  getSeed(): string | null {
    return this.seed;
  }

  /**
   * Seed 값을 수동으로 설정합니다
   */
  setSeed(seed: string): void {
    this.seed = seed;
  }

  /**
   * 네이버 부동산 매물(Article) 목록을 가져옵니다 (모든 페이지)
   */
  async getArticlesAndSave(): Promise<ArticleItem[]> {
    try {
      if (!this.seed) {
        throw new Error(
          "Seed가 설정되지 않았습니다. fetchSeed()를 먼저 호출하세요."
        );
      }

      const allArticles: ArticleItem[] = [];
      let lastInfo: (string | number)[] = [];
      let hasNextPage = true;
      let pageCount = 0;
      let consecutiveErrors = 0;
      const MAX_CONSECUTIVE_ERRORS = 3; // 연속 3번 실패 시 중단

      while (hasNextPage) {
        pageCount++;
        console.log(`페이지 ${pageCount} 가져오는 중...`);

        try {
          const requestData = {
            seed: this.seed,
            size: 30,
            realtorId: this.realtorId,
            userChannelType: "MOBILE",
            tradeTypes: this.tradeTypes,
            realestateTypes: this.realestateTypes,
            articleSortType: "RANKING_DESC",
            lastInfo: lastInfo,
          };

          const response = await axiosInstance.post<{
            result: ArticleResponse;
          }>(`${this.baseUrl}/front-api/v1/realtor/articles`, requestData, {
            adapter: "fetch",
            headers: {
              accept: "application/json, text/plain, */*",
              "accept-language": "ko-KR,ko;q=0.9,en-US;q=0.8,en;q=0.7",
              "cache-control": "no-cache",
              "content-type": "application/json",
              origin: "https://fin.land.naver.com",
              pragma: "no-cache",
              priority: "u=1, i",
              referer: `https://fin.land.naver.com/realtor/${this.realtorId}`,
              "sec-fetch-dest": "empty",
              "sec-fetch-mode": "cors",
              "sec-fetch-site": "same-origin",
              Cookie:
                "NNB=ERRHJ3B5VVSWK; ASID=b761af350000018d167c8d130000005b; BNB_FINANCE_HOME_TOOLTIP_MYASSET=true; NFS=2; nstore_session=npmqPtYh8HtPkburp4IEcy9d; nstore_pagesession=jsNphsqEyoM8SlsLLDd-381033; NAC=UgyDBswfn2TYA; PROP_TEST_KEY=1760119571105.a5e5e536fa19a11517f4e39ceca310f2bd2c6804e95ae55962be128b02f64644; PROP_TEST_ID=14a9b4603364297f7f75567e07ce39d330e3dafdc898450eec6972d68b053d72; SHOW_FIN_BADGE=Y; bnb_tooltip_shown_finance_v1=true; _ga=GA1.1.2003164287.1760119968; bnb_tooltip_shown_payment_v1=true; bnb_tooltip_shown_point_v1=true; _ga_RCM29786SD=GS2.1.s1760119968$o1$g1$t1760120139$j47$l0$h0; SRT30=1760908701; SRT5=1760908701; AMP_MKTG_fe4beb374f=JTdCJTIycmVmZXJyZXIlMjIlM0ElMjJodHRwcyUzQSUyRiUyRmZpbi5sYW5kLm5hdmVyLmNvbSUyRiUyMiUyQyUyMnJlZmVycmluZ19kb21haW4lMjIlM0ElMjJmaW4ubGFuZC5uYXZlci5jb20lMjIlN0Q=; AMP_fe4beb374f=JTdCJTIyZGV2aWNlSWQlMjIlM0ElMjIxMzQ4ZTE0MC0wYTllLTQ2ZGItYTg1YS1hYmUyYmVjOTVjZmQlMjIlMkMlMjJ1c2VySWQlMjIlM0ElMjJjN2Y3ZGIxNy01M2NjLTRmODUtOTIxYi01YjdlNmVlZTE0NzQlMjIlMkMlMjJzZXNzaW9uSWQlMjIlM0ExNzYwOTA4NzA3NTg5JTJDJTIyb3B0T3V0JTIyJTNBZmFsc2UlMkMlMjJsYXN0RXZlbnRUaW1lJTIyJTNBMTc2MDkwODcwNzU5MCUyQyUyMmxhc3RFdmVudElkJTIyJTNBMTA2JTdE; BUC=iQcL84Qq8b3Fzq1_dErVxZdLHIq1gmZ1qSl-tPYP3UY=; NID_SES=AAABhrK/RmXnxgkcGsy6jGV/1lM5FEZvATG6vzFIAn/3qTalbuVqyiqKpKj0SV5m2lQFHB6+AVpCgtQIRtpk5IrtsUXFgE+ff9sHHpVdyHeTQUGoNOGUo4WpPw66ObprE9/zVW9KRBBAT9AqaCsnMN1drQMogkZ1VomnMO6l6Kcjg47oezjSVE6qbJhldN+Q9sYqdXqosj+kvaR7K2+bi/GpGMZ352Zbd+owjX6FcEuaET1UBl35KmIlTz5Z1c3ZixALUOy35TKb16ktT+mNNwXwV+oetJkZCfshA6N6sJDQG8f944LvQeatKy1XW5Ld7tuun8GN3Q69xlGtWe/lB1FpnM87mnzSrq0YwMzT1ABHkKLXQfbd5sQdLgEGVB09o3q0iWWrkzKP5g6qn3mUIIQu6bV41p2zyCapBfx2B06RKTd9E7rn7VBYGWgPuWAzwMRa+WECLyTejEKizPXmv2SYuvP527INYjeLLYuezo2xBWfENbmP0UVFET6fTeLgn9k/6o/wYTFlAGftbgNozttCRxs=; PROP_TEST_ID=7e02e4c10eb2f2c2358bca876c0d7ad0b41ee920553cf666f9f8ffea510fe421; PROP_TEST_KEY=1758430291866.2e161026d60e6da4b6ffc456ba20732ac32391c0294df00f3c0b051eb574277e",
              "user-agent":
                "Mozilla/5.0 (iPhone; CPU iPhone OS 18_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.5 Mobile/15E148 Safari/604.1",
            },
          });

          const result = response.data.result;

          // 매물 추가
          const articles = result.list.map(
            (item) => item.representativeArticleInfo
          );

          console.log(`페이지 ${pageCount}: ${articles.length}개 매물 발견`);

          // 즉시 DB에 저장 (페이지별로)
          if (articles.length > 0) {
            await this.saveArticlesToDB(articles);
            allArticles.push(...articles);
          }

          // 성공 시 오류 카운터 리셋
          consecutiveErrors = 0;

          // 다음 페이지 정보 업데이트
          hasNextPage = result.hasNextPage;
          lastInfo = result.lastInfo;

          // 다음 페이지가 없으면 종료
          if (!hasNextPage) {
            console.log("모든 페이지 가져오기 완료");
            break;
          }

          // API 요청 간격 (선택사항)
          const waitTime = 2000 + Math.floor(Math.random() * 1000);
          console.log(`${waitTime}ms 후 다음 페이지 시도...`);
          await new Promise((resolve) => setTimeout(resolve, waitTime));
        } catch (error) {
          consecutiveErrors++;
          console.error(
            `페이지 ${pageCount} 가져오기 실패 (${consecutiveErrors}/${MAX_CONSECUTIVE_ERRORS}):`,
            error
          );

          // 연속 오류 횟수가 최대치를 초과하면 중단
          if (consecutiveErrors >= MAX_CONSECUTIVE_ERRORS) {
            console.error(
              `연속 ${MAX_CONSECUTIVE_ERRORS}번 실패하여 작업을 중단합니다.`
            );
            console.log(
              `현재까지 ${allArticles.length}개 매물이 DB에 저장되었습니다.`
            );
            break;
          }

          // 재시도 전 대기 (점진적으로 증가)
          const waitTime = 1000 * consecutiveErrors;
          console.log(`${waitTime}ms 후 다음 페이지 시도...`);
          await new Promise((resolve) => setTimeout(resolve, waitTime));

          // lastInfo는 유지하고 계속 진행 (다음 페이지 시도)
          // hasNextPage는 true로 유지되어 루프 계속
        }
      }

      console.log(`총 ${allArticles.length}개의 매물 수집 및 저장 완료`);

      return allArticles;
    } catch (error) {
      throw new Error(`매물 목록 가져오기 실패: ${error}`);
    }
  }

  /**
   * 매물 정보를 DB에 저장합니다
   */
  private async saveArticlesToDB(articles: ArticleItem[]): Promise<void> {
    try {
      for (const article of articles) {
        await prisma.realEstateArticle.upsert({
          where: { articleNumber: article.articleNumber },
          create: {
            articleNumber: article.articleNumber,
            articleName: article.articleName,
            articleDescription:
              article.articleDetail?.articleFeatureDescription,
            realtorId: this.realtorId,
            isActive: true,
            jsonData: article,
            city: article.address.city,
            division: article.address.division,
            sector: article.address.sector,
            xCoordinate: article.address.coordinates.xCoordinate,
            yCoordinate: article.address.coordinates.yCoordinate,
            dealPrice: article.priceInfo.dealPrice.toString(),
            warrantyAmount: article.priceInfo.warrantyPrice.toString(),
            rentAmount: article.priceInfo.rentPrice.toString(),
            managementFeeAmount: article.priceInfo.managementFeeAmount,
            direction: article.articleDetail.direction,
            buildingType: article.buildingType,
            tradeType: article.tradeType,
            realEstateType: article.realEstateType,
            supplySpace: article.spaceInfo.supplySpace,
            exclusiveSpace: article.spaceInfo.exclusiveSpace,
            landSpace: article.spaceInfo.landSpace,
            approvalElapsedYear: article.buildingInfo.approvalElapsedYear,
            verificationType: article.verificationInfo.verificationType,
            isAssociationArticle: article.verificationInfo.isAssociationArticle,
            exposureStartDate: article.verificationInfo.exposureStartDate,
            articleConfirmDate: article.verificationInfo.articleConfirmDate,
            isDirectTrade: article.articleDetail.directTrade,
            floorInfo: article.articleDetail.floorInfo,
            isSafeLessorOfHug: article.articleDetail.isSafeLessorOfHug,
            isVrExposed: article.articleMedia.isVrExposed,
            targetFloor: article.articleDetail.floorDetailInfo.targetFloor,
            totalFloor: article.articleDetail.floorDetailInfo.totalFloor,
          },
          update: {
            articleNumber: article.articleNumber,
            articleName: article.articleName,
            articleDescription:
              article.articleDetail?.articleFeatureDescription,
            realtorId: this.realtorId,
            isActive: true,
            jsonData: article,
            city: article.address.city,
            division: article.address.division,
            sector: article.address.sector,
            xCoordinate: article.address.coordinates.xCoordinate,
            yCoordinate: article.address.coordinates.yCoordinate,
            dealPrice: article.priceInfo.dealPrice.toString(),
            warrantyAmount: article.priceInfo.warrantyPrice.toString(),
            rentAmount: article.priceInfo.rentPrice.toString(),
            managementFeeAmount: article.priceInfo.managementFeeAmount,
            direction: article.articleDetail.direction,
            buildingType: article.buildingType,
            tradeType: article.tradeType,
            realEstateType: article.realEstateType,
            supplySpace: article.spaceInfo.supplySpace,
            exclusiveSpace: article.spaceInfo.exclusiveSpace,
            landSpace: article.spaceInfo.landSpace,
            approvalElapsedYear: article.buildingInfo.approvalElapsedYear,
            verificationType: article.verificationInfo.verificationType,
            isAssociationArticle: article.verificationInfo.isAssociationArticle,
            exposureStartDate: article.verificationInfo.exposureStartDate,
            articleConfirmDate: article.verificationInfo.articleConfirmDate,
            isDirectTrade: article.articleDetail.directTrade,
            floorInfo: article.articleDetail.floorInfo,
            isSafeLessorOfHug: article.articleDetail.isSafeLessorOfHug,
            isVrExposed: article.articleMedia.isVrExposed,
            targetFloor: article.articleDetail.floorDetailInfo.targetFloor,
            totalFloor: article.articleDetail.floorDetailInfo.totalFloor,
          },
        });
      }

      console.log(`${articles.length}개 매물 DB 저장 완료`);
    } catch (error) {
      console.error("DB 저장 실패:", error);
    }
  }

  /**
   * 매물 상세 정보를 DB에 저장합니다
   */
  private async saveArticlesDetailToDB(articles: ArticleItem[]): Promise<void> {
    try {
      for (const article of articles) {
        await prisma.realEstateArticle.update({
          where: { articleNumber: article.articleNumber },
          data: {
            articleNumber: article.articleNumber,
            articleName: article.articleName,
          },
        });
      }

      console.log(`${articles.length}개 매물 DB 저장 완료`);
    } catch (error) {
      console.error("DB 저장 실패:", error);
    }
  }

  /**
   * DB에서 저장된 매물 목록을 가져옵니다
   */
  async getArticlesFromDB() {
    try {
      const articles = await prisma.realEstateArticle.findMany({
        select: {
          id: true,
          articleNumber: true,
          articleName: true,
          buildingType: true,
          tradeType: true,
          realEstateType: true,
          city: true,
          division: true,
          sector: true,
          xCoordinate: true,
          yCoordinate: true,
          dealPrice: true,
          warrantyAmount: true,
          rentAmount: true,
          managementFeeAmount: true,
          totalFloor: true,
          direction: true,
          brokerName: true,
          brokerageName: true,
          cpId: true,
          articleFeature: true,
          imageUrl: true,
          imageCount: true,
          isVrExposed: true,
          verificationType: true,
          exposureStartDate: true,
          articleConfirmDate: true,
          createdAt: true,
          // jsonData는 제외
        },
        orderBy: { createdAt: "desc" },
      });

      return articles;
    } catch (error) {
      throw new Error(`DB에서 매물 목록 가져오기 실패: ${error}`);
    }
  }

  /**
   * 매물 상세 정보를 가져옵니다 (HTML 페이지)
   */
  async getArticleDetail(articleNumber: string): Promise<string> {
    try {
      const response = await axios.get(
        `https://fin.land.naver.com/articles/${articleNumber}`,
        {
          headers: {
            accept:
              "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
            "accept-language":
              "ko-KR,ko;q=0.9,en-US;q=0.8,en;q=0.7,la;q=0.6,zh-CN;q=0.5,zh;q=0.4",
            "cache-control": "no-cache",
            pragma: "no-cache",
            priority: "u=0, i",
            referer: "https://m.land.naver.com/",
            "sec-fetch-dest": "document",
            "sec-fetch-mode": "navigate",
            "sec-fetch-site": "same-origin",
            "sec-fetch-user": "?1",
            "upgrade-insecure-requests": "1",
            "user-agent":
              "Mozilla/5.0 (iPhone; CPU iPhone OS 18_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.5 Mobile/15E148 Safari/604.1",
            Cookie:
              "NACT=1; NNB=ERRHJ3B5VVSWK; ASID=b761af350000018d167c8d130000005b; BNB_FINANCE_HOME_TOOLTIP_MYASSET=true; NFS=2; nstore_session=npmqPtYh8HtPkburp4IEcy9d; nstore_pagesession=jsNphsqEyoM8SlsLLDd-381033; NAC=UgyDBswfn2TYA; PROP_TEST_KEY=1760119571105.a5e5e536fa19a11517f4e39ceca310f2bd2c6804e95ae55962be128b02f64644; PROP_TEST_ID=14a9b4603364297f7f75567e07ce39d330e3dafdc898450eec6972d68b053d72; SHOW_FIN_BADGE=Y; bnb_tooltip_shown_finance_v1=true; _ga=GA1.1.2003164287.1760119968; bnb_tooltip_shown_payment_v1=true; bnb_tooltip_shown_point_v1=true; _ga_RCM29786SD=GS2.1.s1760119968$o1$g1$t1760120139$j47$l0$h0; SRT30=1760908701; AMP_MKTG_fe4beb374f=JTdCJTIycmVmZXJyZXIlMjIlM0ElMjJodHRwcyUzQSUyRiUyRmZpbi5sYW5kLm5hdmVyLmNvbSUyRiUyMiUyQyUyMnJlZmVycmluZ19kb21haW4lMjIlM0ElMjJmaW4ubGFuZC5uYXZlci5jb20lMjIlN0Q=; NACT=1; AMP_fe4beb374f=JTdCJTIyZGV2aWNlSWQlMjIlM0ElMjIxMzQ4ZTE0MC0wYTllLTQ2ZGItYTg1YS1hYmUyYmVjOTVjZmQlMjIlMkMlMjJ1c2VySWQlMjIlM0ElMjJjN2Y3ZGIxNy01M2NjLTRmODUtOTIxYi01YjdlNmVlZTE0NzQlMjIlMkMlMjJzZXNzaW9uSWQlMjIlM0ExNzYwOTA4NzA3NTg5JTJDJTIyb3B0T3V0JTIyJTNBZmFsc2UlMkMlMjJsYXN0RXZlbnRUaW1lJTIyJTNBMTc2MDkwODcwNzU5MCUyQyUyMmxhc3RFdmVudElkJTIyJTNBMTA2JTdE; SRT5=1760910601; BUC=xfph3MjRAi0ASmfAYey0bboZx9l0LuH-hlDSYMk_YVI=; PROP_TEST_ID=7e02e4c10eb2f2c2358bca876c0d7ad0b41ee920553cf666f9f8ffea510fe421; PROP_TEST_KEY=1758430291866.2e161026d60e6da4b6ffc456ba20732ac32391c0294df00f3c0b051eb574277e",
          },
        }
      );

      return response.data;
    } catch (error) {
      throw new Error(`매물 상세 정보 가져오기 실패: ${error}`);
    }
  }
  async resetActiveStatus() {
    console.log("초기화하는중");
    return prisma.realEstateArticle.updateMany({
      where: {
        realtorId: this.realtorId,
      },
      data: {
        isActive: false,
        realtorId: this.realtorId,
      },
    });
  }

  async deleteUnactiveArticles() {
    const result = await prisma.realEstateArticle.deleteMany({
      where: {
        isActive: false,
        realtorId: this.realtorId,
      },
    });
    console.log(`${result.count}개의 비활성 매물 삭제 완료`);
    return result;
  }

  getRealtorId() {
    return this.realtorId;
  }

  /**
   * 프록시를 사용하여 매물 상세 정보를 가져옵니다
   */
  async getArticleDetailWithProxy(articleNumber: string): Promise<string> {
    try {
      const proxyUrl = "http://gw.dataimpulse.com:823";
      const proxyAuth = "0bdeb90b7713c370cdeb__cr.kr:a5ae50d6913bd778";

      const response = await axios.get(
        `https://fin.land.naver.com/articles/${articleNumber}`,
        {
          adapter: "fetch",
          proxy: {
            host: "gw.dataimpulse.com",
            port: 823,
            auth: {
              username: "0bdeb90b7713c370cdeb__cr.kr",
              password: "a5ae50d6913bd778",
            },
          },
          headers: {
            accept:
              "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
            "accept-language":
              "ko-KR,ko;q=0.9,en-US;q=0.8,en;q=0.7,la;q=0.6,zh-CN;q=0.5,zh;q=0.4",
            "cache-control": "no-cache",
            pragma: "no-cache",
            priority: "u=0, i",
            referer: "https://m.land.naver.com/",
            "sec-fetch-dest": "document",
            "sec-fetch-mode": "navigate",
            "sec-fetch-site": "same-origin",
            "sec-fetch-user": "?1",
            "upgrade-insecure-requests": "1",
            "user-agent":
              "Mozilla/5.0 (iPhone; CPU iPhone OS 18_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.5 Mobile/15E148 Safari/604.1",
          },
          timeout: 30000,
        }
      );

      return response.data;
    } catch (error) {
      throw new Error(`프록시를 통한 매물 상세 정보 가져오기 실패: ${error}`);
    }
  }

  /**
   * HTML에서 __NEXT_DATA__ JSON 추출
   */
  parseArticleDetailFromHtml(html: string): any {
    try {
      const regex =
        /<script id="__NEXT_DATA__" type="application\/json"[^>]*>(.*?)<\/script>/s;
      const match = html.match(regex);

      if (!match || !match[1]) {
        throw new Error("__NEXT_DATA__ 스크립트를 찾을 수 없습니다");
      }

      // match[1]은 <script> 태그 안의 JSON 내용만 포함
      const jsonData = JSON.parse(match[1]);
      return jsonData;
    } catch (error) {
      console.error("HTML 파싱 실패:", error);
      return null;
    }
  }

  /**
   * 매물 상세 정보를 DB에 저장
   */
  async saveArticleDetailToDB(
    articleNumber: string,
    detailData: any
  ): Promise<void> {
    try {
      const queries =
        detailData?.props?.pageProps?.dehydratedState?.queries || [];

      // 각 쿼리에서 필요한 데이터 추출
      let basicInfo: any = {};
      let priceInfo: any = {};
      let facilityInfo: any = {};
      let agentInfo: any = {};
      let addressInfo: any = {};
      let images: any[] = [];

      for (const query of queries) {
        const queryKey = query.queryKey?.[0];
        const result = query.state?.data?.result;

        if (queryKey === "GET /article/basicInfo") {
          basicInfo = result?.detailInfo || {};
          priceInfo = result?.priceInfo || {};
        } else if (queryKey === "GET /article/agent") {
          agentInfo = result || {};
        } else if (queryKey === "GET /legalDivision/infoList" && result) {
          const divisionNumbers = Object.keys(result);
          if (divisionNumbers.length > 0 && divisionNumbers[0]) {
            addressInfo = result[divisionNumbers[0]] || {};
          }
        } else if (queryKey === "GET /article/galleryImages") {
          images = result || [];
        }
      }

      // DB 업데이트
      await prisma.realEstateArticle.update({
        where: { articleNumber },
        data: {
          // 가격 정보
          warrantyAmount: priceInfo.warrantyAmount,
          rentAmount: priceInfo.rentAmount,
          loan: priceInfo.loan,
          loanCode: priceInfo.loanCode,
          loanTypeCode: priceInfo.loanTypeCode,

          // 위치 정보
          city: addressInfo.cityName,
          division: addressInfo.divisionName,
          sector: addressInfo.sectorName,
          jibun: basicInfo.detailInfo?.articleDetailInfo?.jibun,
          fullAddress: addressInfo.fullAddress,
          isAddressExposed:
            basicInfo.detailInfo?.articleDetailInfo?.isAddressExposed,
          xCoordinate: addressInfo.coordinates?.xCoordinate,
          yCoordinate: addressInfo.coordinates?.yCoordinate,
          legalDivisionNumber: addressInfo.legalDivisionNumber,

          // 건물 정보
          buildingUse: basicInfo.detailInfo?.articleDetailInfo?.buildingUse,
          buildingConjunctionDate:
            basicInfo.detailInfo?.facilityInfo?.buildingConjunctionDate,
          buildingConjunctionDateType:
            basicInfo.detailInfo?.facilityInfo?.buildingConjunctionDateType,
          approvalElapsedYear:
            basicInfo.detailInfo?.facilityInfo?.approvalElapsedYear,
          totalParkingCount:
            basicInfo.detailInfo?.facilityInfo?.totalParkingCount,
          isParkingPossible:
            basicInfo.detailInfo?.facilityInfo?.isParkingPossible,
          isIllegalBuilding:
            basicInfo.detailInfo?.articleDetailInfo?.isIllegalBuilding,

          // 공간 정보
          supplySpace: basicInfo.detailInfo?.sizeInfo?.supplySpace,
          exclusiveSpace: basicInfo.detailInfo?.sizeInfo?.exclusiveSpace,
          landSpace: basicInfo.detailInfo?.sizeInfo?.landShare,
          targetFloor: basicInfo.detailInfo?.spaceInfo?.floorInfo?.targetFloor,
          totalFloor: basicInfo.detailInfo?.spaceInfo?.floorInfo?.totalFloor,
          groundTotalFloor:
            basicInfo.detailInfo?.spaceInfo?.floorInfo?.groundTotalFloor,
          undergroundTotalFloor:
            basicInfo.detailInfo?.spaceInfo?.floorInfo?.undergroundTotalFloor,
          floorType: basicInfo.detailInfo?.spaceInfo?.floorInfo?.floorType,
          residenceType:
            basicInfo.detailInfo?.spaceInfo?.floorInfo?.residenceType,
          roomCount: basicInfo.detailInfo?.spaceInfo?.roomCount,
          bathRoomCount: basicInfo.detailInfo?.spaceInfo?.bathRoomCount,
          direction: basicInfo.detailInfo?.spaceInfo?.direction,
          directionStandard: basicInfo.detailInfo?.spaceInfo?.directionStandard,
          duplex: basicInfo.detailInfo?.spaceInfo?.duplex,

          // 입주 정보
          movingInNegotiation:
            basicInfo.detailInfo?.movingInInfo?.movingInNegotiation,
          movingInDate: basicInfo.detailInfo?.movingInInfo?.movingInDate,
          movingInType: basicInfo.detailInfo?.movingInInfo?.movingInType,

          // 중개사 정보
          brokerName: agentInfo.brokerName,
          brokerageName: agentInfo.brokerageName,
          brokerId: agentInfo.brokerId,
          brokerAddress: agentInfo.address,
          brokerPhone: agentInfo.phone?.mobile,
          businessRegistrationNumber: agentInfo.businessRegistrationNumber,
          ownerConfirmationSaleCount: agentInfo.ownerConfirmationSaleCount,

          // 매물 설명
          articleDescription:
            basicInfo.detailInfo?.articleDetailInfo?.articleDescription,
          isDirectTrade: basicInfo.detailInfo?.articleDetailInfo?.isDirectTrade,
          isSafeLessorOfHug:
            basicInfo.detailInfo?.articleDetailInfo?.isSafeLessorOfHug,

          // 미디어
          imageUrl: images[0]?.imageUrl,
          imageCount: images.length,
          isVrExposed: images.some((img: any) => img.isVrExposed),

          // 검증 정보
          verificationType:
            basicInfo.detailInfo?.verificationInfo?.verificationType,
          isAssociationArticle:
            basicInfo.detailInfo?.verificationInfo?.isAssociationArticle,
          exposureStartDate:
            basicInfo.detailInfo?.verificationInfo?.exposureStartDate,
          articleConfirmDate:
            basicInfo.detailInfo?.verificationInfo?.articleConfirmDate,

          // 편의시설
          facilityLife: JSON.stringify(
            basicInfo.detailInfo?.facilityInfo?.life || []
          ),
          facilitySecurity: JSON.stringify(
            basicInfo.detailInfo?.facilityInfo?.security || []
          ),
          facilityEtc: JSON.stringify(
            basicInfo.detailInfo?.facilityInfo?.etc || []
          ),
          facilityAircon: JSON.stringify(
            basicInfo.detailInfo?.facilityInfo?.aircon || []
          ),

          // 전체 JSON 데이터 업데이트
          jsonData: detailData,
        },
      });
    } catch (error) {
      throw new Error(`DB 저장 실패: ${error}`);
    }
  }

  async updateArticleDetaiAddressWithProxy() {
    try {
      const firstPageResponse = await axiosInstance.get(
        `https://m.land.naver.com/agency/info/list?rltrMbrId=${this.realtorId}&tradTpCd=&atclRletTpCd=&tradeTypeChange=false&page=1`,
        {
          adapter: "fetch",
          proxy: {
            host: "gw.dataimpulse.com",
            port: 823,
            auth: {
              username: "0bdeb90b7713c370cdeb__cr.kr",
              password: "a5ae50d6913bd778",
            },
          },
          headers: {
            connection: "close",
            accept:
              "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
            "accept-language": "ko-KR,ko;q=0.9",
            "cache-control": "no-cache",
            pragma: "no-cache",
            priority: "u=0, i",
            "sec-fetch-dest": "document",
            "sec-fetch-mode": "navigate",
            "sec-fetch-site": "none",
            "sec-fetch-user": "?1",
            "upgrade-insecure-requests": "1",
            "User-Agent":
              "Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1",
          },
        }
      );

      const totalCnt = firstPageResponse.data.totalCnt;
      const totalPage = Math.ceil(totalCnt / 20);

      function sleep(ms: number) {
        return new Promise((resolve) => setTimeout(resolve, ms));
      }

      const BATCH_SIZE = 3;
      const DELAY = 10000; // 10초

      for (let i = 1; i <= totalPage; i += BATCH_SIZE) {
        const group = [];

        for (let page = i; page < i + BATCH_SIZE && page <= totalPage; page++) {
          group.push(updateAddress(page, this.realtorId));
        }

        console.log(`Requesting pages: ${i} ~ ${i + group.length - 1}`);

        await Promise.allSettled(group);

        console.log(`Batch done. Waiting ${DELAY / 1000}s...`);
        await sleep(DELAY);
      }

      console.log("✅ 모든 페이지 처리 완료");
    } catch (error) {
      throw new Error(`프록시를 통한 매물 상세 정보 가져오기 실패: ${error}`);
    }

    async function updateAddress(page: number, realtorId: string) {
      const response = await axiosInstance.get(
        `https://m.land.naver.com/agency/info/list?rltrMbrId=${realtorId}&tradTpCd=&atclRletTpCd=&tradeTypeChange=false&page=${page}`,
        {
          adapter: "fetch",
          proxy: {
            host: "gw.dataimpulse.com",
            port: 823,
            auth: {
              username: "0bdeb90b7713c370cdeb__cr.kr",
              password: "a5ae50d6913bd778",
            },
          },
          headers: {
            connection: "close",
            accept:
              "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
            "accept-language": "ko-KR,ko;q=0.9",
            "cache-control": "no-cache",
            pragma: "no-cache",
            priority: "u=0, i",
            "sec-fetch-dest": "document",
            "sec-fetch-mode": "navigate",
            "sec-fetch-site": "none",
            "sec-fetch-user": "?1",
            "upgrade-insecure-requests": "1",
            "User-Agent":
              "Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1",
          },
        }
      );
      const data = response.data;

      // list 순회하면서 detailAddress 업데이트
      if (data.list && Array.isArray(data.list)) {
        console.log(`페이지 ${page}: ${data.list.length}개 매물 처리 중...`);

        for (const item of data.list) {
          try {
            // atclNo(매물번호)로 DB에서 매물 찾기
            const existingArticle = await prisma.realEstateArticle.findUnique({
              where: {
                articleNumber: item.atclNo,
              },
            });

            if (existingArticle) {
              // detailAddress 업데이트
              await prisma.realEstateArticle.update({
                where: {
                  articleNumber: item.atclNo,
                },
                data: {
                  detailAddress: item.dtlAddr || null,
                  direction: item.direction || null,
                  cpId: item.cpid || null,
                  cpNm: item.cpNm || null,
                  tradTpNm: item.tradTpNm || null,
                  prcInfo: item.prcInfo || null,
                  leasePrc: item.leasePrc || null,
                  atclFetrDesc: item.atclFetrDesc || null,
                  atclCfmYmd: item.atclCfmYmd || null,
                  rentAmount: item.rentPrc || null,
                  warrantyAmount: item.leasePrc || null,
                },
              });

              console.log(
                `✅ ${item.atclNo} - detailAddress 업데이트: ${item.dtlAddr}`
              );
            } else {
              console.log(`⚠️ ${item.atclNo} - DB에 존재하지 않는 매물`);
            }
          } catch (error) {
            console.error(`❌ ${item.atclNo} 업데이트 실패:`, error);
          }
        }
      }
    }
  }

  async getCortarNoAndLgeo(
    article: RealEstateArticle
  ): Promise<{ cortarNo: string | undefined; lgeo: string | undefined }> {
    try {
      const lft = article.xCoordinate || 0 + 0.000283244;
      const rgt = article.xCoordinate || 0 - 0.000283244;
      const top = article.yCoordinate || 0 + 0.000283244;
      const btm = article.yCoordinate || 0 - 0.000283244;

      const url = `https://m.land.naver.com/cluster/clusterList?view=atcl&rletTpCd=APT:OPST:VL:YR:DSD:ABYG:OBYG:JGC:JWJT:DDDGG:SGJT:JGB:OR:SG:SMS:GJCG:GM:TJ:APTHGJ&tradTpCd=A1:B1:B2:B3&z=19&lat=${article.yCoordinate}&lon=${article.xCoordinate}&btm=${btm}&lft=${lft}&top=${top}&rgt=${rgt}&pCortarNo=&addon=COMPLEX&isOnlyIsale=false`;
      const response = await axiosInstance.get(url, {
        adapter: "fetch",
        proxy: {
          host: "gw.dataimpulse.com",
          port: 823,
          auth: {
            username: "0bdeb90b7713c370cdeb__cr.kr",
            password: "a5ae50d6913bd778",
          },
        },
        headers: {
          Connection: "close",
          accept: "application/json, text/javascript, */*; q=0.01",
          "accept-language": "ko;q=0.7",
          "cache-control": "no-cache",
          pragma: "no-cache",
          priority: "u=1, i",
          referer: "https://m.land.naver.com/",
          "sec-ch-ua":
            '"Brave";v="141", "Not?A_Brand";v="8", "Chromium";v="141"',
          "sec-ch-ua-mobile": "?1",
          "sec-ch-ua-platform": '"Android"',
          "sec-fetch-dest": "empty",
          "sec-fetch-mode": "cors",
          "sec-fetch-site": "same-origin",
          "sec-gpc": "1",
          "user-agent":
            "Mozilla/5.0 (Linux; Android 8.0.0; SM-G955U Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Mobile Safari/537.36",
          "x-requested-with": "XMLHttpRequest",
        },
      });
      article.cortarNo = response.data.cortar.detail.cortarNo;

      const markers = response.data.data.ARTICLE;
      const currentLocation = {
        latitude: article.yCoordinate as number,
        longitude: article.xCoordinate as number,
      };

      // markers를 geolib 형식으로 변환
      const markersWithCoords = markers.map((m: any) => ({
        latitude: m.lat,
        longitude: m.lon,
        lgeo: m.lgeo,
      }));

      // 가장 가까운 마커 찾기
      const nearestCoords = findNearest(currentLocation, markersWithCoords);

      // 원본 마커 데이터에서 lgeo 찾기
      const nearestMarker = markersWithCoords.find(
        (m: any) =>
          m.latitude === (nearestCoords as any).latitude &&
          m.longitude === (nearestCoords as any).longitude
      );

      console.log(
        `✅ ${article.articleNumber} - cortarNo: ${response.data.cortar?.detail?.cortarNo}, lgeo: ${nearestMarker?.lgeo}`
      );
      return {
        cortarNo: response.data.cortar?.detail?.cortarNo,
        lgeo: nearestMarker?.lgeo,
      };
    } catch (error) {
      console.error(`❌ 오류 발생:`, error);
      return {
        cortarNo: undefined,
        lgeo: undefined,
      };
    }
  }

  async getRanking(
    article: RealEstateArticle,
    token: string,
    cookie: string
  ): Promise<number> {
    try {
      const lft = article.xCoordinate || 0 + 0.000283244;
      const rgt = article.xCoordinate || 0 - 0.000283244;
      const top = article.yCoordinate || 0 + 0.000283244;
      const btm = article.yCoordinate || 0 - 0.000283244;

      const url = `https://new.land.naver.com/api/articles?markerId=${article.lgeo}&markerType=LGEOHASH_MIX_ARTICLE&prevScrollTop=0&order=rank&realEstateType=${article.realEstateType}&tradeType=${article.tradeType}&rentPriceMin=0&rentPriceMax=900000000&priceMin=0&priceMax=900000000&areaMin=0&areaMax=900000000&oldBuildYears&recentlyBuildYears&minHouseHoldCount&maxHouseHoldCount&showArticle=false&sameAddressGroup=false&minMaintenanceCost&maxMaintenanceCost&priceType=RETAIL&directions=&page=1&articleState`;

      const response = await axiosInstance.get(url, {
        adapter: "fetch",
        proxy: {
          host: "gw.dataimpulse.com",
          port: 823,
          auth: {
            username: "0bdeb90b7713c370cdeb__cr.kr",
            password: "a5ae50d6913bd778",
          },
        },
        headers: {
          Connection: "close",
          accept: "*/*",
          "accept-language":
            "ko-KR,ko;q=0.9,en-US;q=0.8,en;q=0.7,la;q=0.6,zh-CN;q=0.5,zh;q=0.4",
          "cache-control": "no-cache",
          pragma: "no-cache",
          priority: "u=1, i",
          referer: `https://new.land.naver.com/offices?ms=37.5650651,126.9309659,18&a=${article.realEstateType}&b=${article.tradeType}&e=RETAIL`,
          "sec-ch-ua":
            '"Chromium";v="142", "Google Chrome";v="142", "Not_A Brand";v="99"',
          "sec-ch-ua-mobile": "?0",
          "sec-ch-ua-platform": '"Windows"',
          "sec-fetch-dest": "empty",
          "sec-fetch-mode": "cors",
          "sec-fetch-site": "same-origin",
          "user-agent":
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36",
          "Content-Type": "text/plain",
          Authorization: `Bearer ${token}`,
          Cookie: cookie,
        },
      });

      // body 배열에서 articleNumber와 일치하는 atclNo 찾기
      const rankingList = response.data.articleList || [];
      const index = rankingList.findIndex(
        (item: any) => item.articleNo === article.articleNumber
      );

      // index가 -1이면 찾지 못한 것이므로 99 반환, 아니면 index + 1 반환
      const ranking = index === -1 ? 99 : index + 1;

      console.log(
        `✅ ${article.articleNumber} - ranking: ${ranking} (${
          index === -1 ? "순위 없음" : `${index}번째`
        })`
      );

      return ranking;
    } catch (error) {
      console.error(`❌ 오류 발생:`, error);
      return 99;
    }
  }

  async updateBrokerInfo(articleNumber: string, cookieString: string) {
    try {
      const url = `https://fin.land.naver.com/front-api/v1/article/agent?articleNumber=${articleNumber}`;

      const response = await axiosInstance.get(url, {
        adapter: "fetch",
        proxy: {
          host: "gw.dataimpulse.com",
          port: 823,
          auth: {
            username: "0bdeb90b7713c370cdeb__cr.kr",
            password: "a5ae50d6913bd778",
          },
        },
        headers: {
          accept:
            "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8",
          "accept-language": "ko;q=0.7",
          "cache-control": "no-cache",
          pragma: "no-cache",
          priority: "u=0, i",
          referer: "https://m.land.naver.com/",
          "sec-fetch-dest": "document",
          "sec-fetch-mode": "navigate",
          "sec-fetch-site": "same-site",
          "sec-fetch-user": "?1",
          "sec-gpc": "1",
          "upgrade-insecure-requests": "1",
          "user-agent":
            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.5 Safari/605.1.15",
          cookie: cookieString,
        },
      });

      const brokerInfo = response.data.result;

      // DB 업데이트
      await prisma.realEstateArticle.update({
        where: {
          articleNumber: articleNumber,
        },
        data: {
          brokerName: brokerInfo.brokerName || null,
          brokerPhone: brokerInfo.phone?.mobile || null,
          brokerAddress: brokerInfo.address || null,
          brokerageName: brokerInfo.brokerageName || null,
        },
      });

      console.log(`✅ ${articleNumber} - 중개사 정보 업데이트 완료`);
    } catch (error) {
      console.error(`❌ 오류 발생:`, error);
    }
  }
  async getActiveArticles(realtorId: string) {
    try {
      const articles = await prisma.realEstateArticle.findMany({
        where: {
          realtorId: realtorId,
          isActive: true,
        },
      });
      return articles;
    } catch (error) {
      console.error(`❌ 오류 발생:`, error);
      return [];
    }
  }

  async getApiCookie() {
    try {
      // 첫 번째 요청으로 쿠키 가져오기
      const initialResponse = await axios.get(
        "https://fin.land.naver.com/?content=recent",
        {
          adapter: "fetch",
          proxy: {
            host: "gw.dataimpulse.com",
            port: 823,
            auth: {
              username: "0bdeb90b7713c370cdeb__cr.kr",
              password: "a5ae50d6913bd778",
            },
          },
          headers: {
            accept:
              "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
            "accept-language":
              "ko-KR,ko;q=0.9,en-US;q=0.8,en;q=0.7,la;q=0.6,zh-CN;q=0.5,zh;q=0.4",
            "cache-control": "no-cache",
            pragma: "no-cache",
            priority: "u=0, i",
            "sec-ch-ua":
              '"Chromium";v="142", "Google Chrome";v="142", "Not_A Brand";v="99"',
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-platform": '"Windows"',
            "sec-fetch-dest": "document",
            "sec-fetch-mode": "navigate",
            "sec-fetch-site": "same-origin",
            "sec-fetch-user": "?1",
            "upgrade-insecure-requests": "1",
            "user-agent":
              "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36",
          },
        }
      );

      // Set-Cookie 헤더에서 쿠키 추출
      const cookies = initialResponse.headers["set-cookie"];
      const cookieString = cookies
        ? cookies.map((cookie) => cookie.split(";")[0]).join("; ")
        : "";

      return cookieString;
    } catch (error) {
      console.error(`❌ 오류 발생:`, error);
      return "";
    }
  }
}
