import { Injectable, Logger } from '@nestjs/common';
import { HttpService } from '@nestjs/axios';
import { firstValueFrom } from 'rxjs';
import { TokenService } from './token.service';
import axios, { AxiosRequestConfig } from 'axios';
import { Cron } from '@nestjs/schedule';
import { TelegramService, ChatId } from './telegram.service';
import { ProxyService } from './proxy.service';
import { HttpsProxyAgent } from 'https-proxy-agent';

interface AccountObject {
  status: string; 
  balance?: number;
  data?: Object;
}

@Injectable()
export class AdminService {
  private readonly logger = new Logger(AdminService.name);

    constructor(
      private readonly httpService: HttpService, 
      private readonly tokenService: TokenService,
      private readonly telegramService: TelegramService,
      private readonly proxyService: ProxyService,
    ) {}

    async depositPoints(userId: string, points: number ) {
        const url = 'https://www.svn-288.com/service/agent/adjustBalance';

        const proxy = await this.proxyService.getProxy();
        if(!proxy){
          this.logger.error('No proxy found');
          return {
            status:  "PROXY_NOT_FOUND",
          }
        }
        const proxyAgent = new HttpsProxyAgent("http://"+proxy);



        const token = await this.tokenService.getActiveToken();
        if(!token){
            return "No Token Found";
        }
    
        const headers = {
            'accept': 'application/json, text/javascript, */*; q=0.01',
            'accept-language': 'en-US,en;q=0.9',
            'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'cookie': 'JSESSIONID='+token+'; language=en; turnoverFilter=10000; winloseFilter=0',
            'origin': 'https://www.svn-288.com',
            'priority': 'u=1, i',
            'referer': 'https://www.svn-288.com/page/agent/playerList.jsp',
            'sec-ch-ua': '"Google Chrome";v="131", "Chromium";v="131", "Not_A Brand";v="24"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"macOS"',
            'sec-fetch-dest': 'empty',
            'sec-fetch-mode': 'cors',
            'sec-fetch-site': 'same-origin',
            'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
            'x-requested-with': 'XMLHttpRequest',
        };
    
        const data = new URLSearchParams({
            userID: userId,
            webSiteType: '0',
            adjBalance: String(points),
            isDeposit: 'true',
            remark: '',
            turnoverRequired: '',
            isCleanTurnoverRequired: 'false',
            isAdjustTurnover: 'false',
            bonusPlatformLimits: '',
            bonusGameTypeLimits: '',
            isOnlyPlayBonusGames: 'false',
            adjBonus: '',
        }).toString();
    
        try {
            const response = await firstValueFrom(
                this.httpService.post(url, data, { headers, httpsAgent: proxyAgent })
            );
            return response.data;
        } catch (error) {
            console.error(error);
            throw error;
        }
    }

    async withdrawPoints(userId: string, points: number ) {
        const url = 'https://www.svn-288.com/service/agent/adjustBalance';

        const proxy = await this.proxyService.getProxy();
        if(!proxy){
          this.logger.error('No proxy found');
          return {
            status:  "PROXY_NOT_FOUND",
          }
        }
        const proxyAgent = new HttpsProxyAgent("http://"+proxy);

        const token = await this.tokenService.getActiveToken();
        if(!token){
            return "No Token Found";
        }
    
        const headers = {
            'accept': 'application/json, text/javascript, */*; q=0.01',
            'accept-language': 'en-US,en;q=0.9',
            'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'cookie': 'JSESSIONID='+token+'; language=en; turnoverFilter=10000; winloseFilter=0',
            'origin': 'https://www.svn-288.com',
            'priority': 'u=1, i',
            'referer': 'https://www.svn-288.com/page/agent/playerList.jsp',
            'sec-ch-ua': '"Google Chrome";v="131", "Chromium";v="131", "Not_A Brand";v="24"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"macOS"',
            'sec-fetch-dest': 'empty',
            'sec-fetch-mode': 'cors',
            'sec-fetch-site': 'same-origin',
            'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
            'x-requested-with': 'XMLHttpRequest',
        };
    
        const data = new URLSearchParams({
            userID: userId,
            webSiteType: '0',
            adjBalance: String(points),
            isDeposit: 'false',
            remark: '',
            turnoverRequired: '',
            isCleanTurnoverRequired: 'false',
            isAdjustTurnover: 'false',
            bonusPlatformLimits: '',
            bonusGameTypeLimits: '',
            isOnlyPlayBonusGames: 'false',
            adjBonus: '',
        }).toString();
    
        try {
            const response = await firstValueFrom(
                this.httpService.post(url, data, { headers, httpsAgent: proxyAgent })
            );
            return response.data;
        } catch (error) {
            console.error(error);
            throw error;
        }
    }

    async checkBalance(userId: string): Promise<{ status: string; balance?: number }> {
        const url = 'https://www.svn-288.com/service/agent/memberlist/search';

        const proxy = await this.proxyService.getProxy();
        if(!proxy){
          this.logger.error('No proxy found');
          return {
            status:  "PROXY_NOT_FOUND",
          }
        }
        const proxyAgent = new HttpsProxyAgent("http://"+proxy);

        const token = await this.tokenService.getActiveToken();
        if(!token){
            return {
                status: "NO_TOKEN_FOUND"
            };
        }
        
        const headers = {
          'accept': 'application/json, text/javascript, */*; q=0.01',
          'accept-language': 'en-US,en;q=0.9,vi;q=0.8',
          'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
          'cookie': 'JSESSIONID='+token,
          'origin': 'https://www.svn-288.com',
          'referer': `https://www.svn-288.com/page/agent/playerList.jsp?queryUserId=${userId}`,
          'sec-ch-ua': '"Chromium";v="116", "Not)A;Brand";v="24", "Google Chrome";v="116"',
          '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/116.0.0.0 Safari/537.36',
          'x-requested-with': 'XMLHttpRequest',
        };
    
        const data = new URLSearchParams({
          queryUserId: userId,
          accountStatus: '-1',
          webSiteType: '-1',
          isInternal: '0',
          pageNumber: '1',
          pageSize: '500',
          isSearchPlayer: 'true',
          sortCreateTimeKey: '',
          tagId: '-1',
          queryTel: '',
          isAffiliate: '-1',
        }).toString();
    
        try {
          const response = await firstValueFrom(
            this.httpService.post(url, data, { headers, httpsAgent: proxyAgent })
          );
    
          const responseData = response.data;
    
          if (responseData.error) {
            if (['Sorry!! Please Sign in.', 'You have been logged off because you have logged on at another location.'].includes(responseData.error)) {
              return { status: 'LOGIN_FAILED' };
            }
          }
    
          if (responseData && responseData.data && responseData.data.length > 0) {
            return {
              status: 'SUCCESS',
              balance: responseData.data[0].balance,
            };
          } else {
            return { status: 'INCORRECT_USERNAME' };
          }
        } catch (error) {
          console.error('Daga Admin Service: checkBalance - error', error.message);
          return { status: '500 server error' };
        }
    }

    async getMainAccountBalance(): Promise<AccountObject> {
      const url = 'https://www.sv288.com/page/agent/subAccountProfile.jsp';

      const proxy = await this.proxyService.getProxy();
      if(!proxy){
        this.logger.error('No proxy found');
        return {
          status:  "PROXY_NOT_FOUND",
        }
      }
      const proxyAgent = new HttpsProxyAgent("http://"+proxy);

      const token = await this.tokenService.getActiveToken();
      if(!token){
          return {
              status: "NO_TOKEN_FOUND"
          };
      }

      const headers: AxiosRequestConfig['headers'] = {
        authority: 'www.sv288.com',
        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': 'en-US,en;q=0.9,vi;q=0.8',
        'cache-control': 'max-age=0',
        cookie: `JSESSIONID=${token}`,
        referer: 'https://www.sv288.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 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1',
      };

      try {
        const response = await axios.get(url, { headers, httpsAgent: proxyAgent });
        const data = response.data;

        const pattern = /MenuConfig\.balance\s*=\s*([\d\.]+)/;
        const matches = data.match(pattern);

        if (matches && matches[1]) {
          return {
            status: "SUCCESS",
            balance: parseFloat(matches[1])
          };
        }
        return {
          status: "FAILED",
          data: data
        }; // Return the raw response if pattern match fails
      } catch (error) {
        return {
          status: "FAILED",
          data: error
        }; 
      }
    }

    @Cron('0 */15 * * * *')
    async getMainBalance15Mins(): Promise<void>{
      let balanceData: AccountObject;
      try{
        balanceData = await this.getMainAccountBalance();
      }catch(error){
        this.telegramService.sendMessage(ChatId.GROUP_LOGGING, "Fetch Balance Error: "+ JSON.stringify(error));
      }
      if(balanceData && balanceData.status === "SUCCESS"){
        this.telegramService.sendMessage(ChatId.GROUP_LOGGING, "apai7001 Current Balance is: "+ balanceData.balance);
      }else{
        this.telegramService.sendMessage(ChatId.GROUP_LOGGING, "apai7001 Current Couldnt be fetched. Error: "+ JSON.stringify(balanceData));
      }
    }
}

