const axios = require('axios');
const https = require('https');
const config = require('./config');

// Créer un client axios pour Gitea (ignorer les certificats auto-signés si nécessaire)
const giteaClient = axios.create({
  baseURL: `${config.gitea.url}/api/v1`,
  auth: {
    username: config.gitea.username,
    password: config.gitea.password,
  },
  httpsAgent: new https.Agent({ rejectUnauthorized: false }),
  timeout: 10000,
});

/**
 * Récupérer les informations d'un dépôt
 */
async function getRepo(owner, repo) {
  try {
    const response = await giteaClient.get(`/repos/${owner}/${repo}`);
    return response.data;
  } catch (err) {
    console.error(`Erreur Gitea getRepo ${owner}/${repo}:`, err.message);
    return null;
  }
}

/**
 * Récupérer les derniers commits d'un dépôt
 */
async function getCommits(owner, repo, limit = 10) {
  try {
    const response = await giteaClient.get(`/repos/${owner}/${repo}/commits`, {
      params: { limit, page: 1 },
    });
    return response.data.map((c) => ({
      sha: c.sha,
      shortSha: c.sha.substring(0, 7),
      message: c.commit.message,
      author: c.commit.author.name,
      date: c.commit.author.date,
      url: c.html_url,
    }));
  } catch (err) {
    console.error(`Erreur Gitea getCommits ${owner}/${repo}:`, err.message);
    return [];
  }
}

/**
 * Récupérer les branches d'un dépôt
 */
async function getBranches(owner, repo) {
  try {
    const response = await giteaClient.get(`/repos/${owner}/${repo}/branches`);
    return response.data.map((b) => ({
      name: b.name,
      commit: b.commit.id.substring(0, 7),
      commitMessage: b.commit.message,
    }));
  } catch (err) {
    console.error(`Erreur Gitea getBranches ${owner}/${repo}:`, err.message);
    return [];
  }
}

/**
 * Récupérer tous les dépôts (avec retry en cas d'erreur DNS)
 */
async function listRepos(retries = 3) {
  for (let i = 0; i < retries; i++) {
    try {
      const response = await giteaClient.get('/repos/search', {
        params: { limit: 50 },
      });
      return response.data.data || [];
    } catch (err) {
      console.error(`Erreur Gitea listRepos (tentative ${i + 1}/${retries}):`, err.message);
      if (i < retries - 1) {
        await new Promise((r) => setTimeout(r, 2000));
      }
    }
  }
  return [];
}

/**
 * Créer un nouveau dépôt
 */
async function createRepo(name, description, isPrivate = true) {
  try {
    const response = await giteaClient.post('/user/repos', {
      name,
      description,
      private: isPrivate,
      auto_init: true,
      default_branch: 'main',
    });
    return response.data;
  } catch (err) {
    console.error(`Erreur Gitea createRepo ${name}:`, err.message);
    throw err;
  }
}

module.exports = {
  getRepo,
  getCommits,
  getBranches,
  listRepos,
  createRepo,
  giteaClient,
};
