'use strict';

// Axios kütüphanesini import ediyoruz.
const axios = require('axios').default;
// URL sınıfını kullanıyoruz.
const { URL } = require('url');

// RapidgatorHost sınıfını tanımlıyoruz.
class RapidgatorHost {
  constructor() {
    // Rapidgator'ün alternatif domain adlarını alias içinde saklıyoruz.
    this.alias = ["rg.to"];
    // Otomatik hesap silme özelliğini true olarak belirliyoruz.
    this.autoDeleteAccount = true;
    // API kullanımını false olarak belirliyoruz.
    this.useAPI = false;
  }

  // Kullanıcı girişi işlevini tanımlıyoruz.
  async login(username, password) {
    try {
      // Giriş URL'sini belirliyoruz.
      const loginUrl = 'https://rapidgator.net/auth/login';
      // Axios ile giriş yapma isteği gönderiyoruz.
      const response = await axios.post(loginUrl, {
        "LoginForm[email]": username,
        "LoginForm[password]": password,
        "LoginForm[rememberMe]": 1
      }, { withCredentials: true });

      // Yanıtta dönen çerezleri alıyoruz.
      const cookies = response.headers['set-cookie'];
      // Eğer çerez yoksa bir hata fırlatıyoruz.
      if (!cookies) {
        throw new Error('Login failed: No cookies returned');
      }

      // Çerezleri birleştirerek döndürüyoruz.
      return cookies.join('; ');
    } catch (error) {
      // Hata durumunda bir hata fırlatıyoruz.
      throw new Error(`Login failed: ${error.message}`);
    }
  }

  // Hesap durumu kontrol işlevini tanımlıyoruz.
  async check(cookie) {
    try {
      // Profil URL'sini belirliyoruz.
      const profileUrl = 'https://rapidgator.net/profile/index';
      // Axios ile hesap kontrolü isteği gönderiyoruz.
      const response = await axios.get(profileUrl, {
        headers: { Cookie: cookie },
        withCredentials: true
      });

      // Yanıtı analiz ederek kullanıcının premium olup olmadığını ve bant genişliğini alıyoruz.
      const isPremium = !/premium">Free</.test(response.data);
      const bandwidthMatch = response.data.match(/Bandwidth available<\/td>\s*<td>(.*)<\/td>/);
      const bandwidthAvailable = bandwidthMatch ? bandwidthMatch[1].trim() : 'Unknown';

      // Bilgileri döndürüyoruz.
      return { isPremium, bandwidthAvailable };
    } catch (error) {
      // Hata durumunda bir hata fırlatıyoruz.
      throw new Error(`Account check failed: ${error.message}`);
    }
  }

  // Dosya indirme işlevini tanımlıyoruz.
  async download(link, cookie) {
    try {
      // İndirme bağlantısını HEAD isteği ile kontrol ediyoruz.
      let response = await axios.head(link, { withCredentials: true, headers: { Cookie: cookie } });

      // Eğer yönlendirme varsa yeni bağlantıyı alıyoruz.
      if (response.status >= 300 && response.status < 400) {
        link = response.headers.location;
      }

      // Dosyayı indiriyoruz.
      response = await axios.get(link, {
        responseType: 'stream',
        headers: { Cookie: cookie },
        withCredentials: true
      });

      // İndirilen dosyanın verisini döndürüyoruz.
      return response.data;
    } catch (error) {
      // Hata durumunda bir hata fırlatıyoruz.
      throw new Error(`Download failed: ${error.message}`);
    }
  }
}

// RapidgatorHost sınıfını dışarıya aktarıyoruz.
module.exports = RapidgatorHost;