/**
 * TASKMATE - Gitea Route
 * ======================
 * API-Endpoints für Gitea-Integration
 */

const express = require('express');
const router = express.Router();
const giteaService = require('../services/giteaService');
const logger = require('../utils/logger');

/**
 * GET /api/gitea/test
 * Gitea-Verbindung testen
 */
router.get('/test', async (req, res) => {
  try {
    const result = await giteaService.testConnection();
    res.json(result);
  } catch (error) {
    logger.error('Fehler beim Testen der Gitea-Verbindung:', error);
    res.status(500).json({
      success: false,
      connected: false,
      error: error.message
    });
  }
});

/**
 * GET /api/gitea/repositories
 * Alle verfügbaren Repositories auflisten
 */
router.get('/repositories', async (req, res) => {
  try {
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 50;

    const result = await giteaService.listRepositories({ page, limit });
    res.json(result);
  } catch (error) {
    logger.error('Fehler beim Auflisten der Repositories:', error);
    res.status(500).json({ success: false, error: error.message });
  }
});

/**
 * POST /api/gitea/repositories
 * Neues Repository erstellen
 */
router.post('/repositories', async (req, res) => {
  try {
    const { name, description, private: isPrivate, autoInit, defaultBranch } = req.body;

    if (!name) {
      return res.status(400).json({ error: 'Repository-Name ist erforderlich' });
    }

    const result = await giteaService.createRepository(name, {
      description,
      private: isPrivate !== false,
      autoInit: autoInit !== false,
      defaultBranch: defaultBranch || 'main'
    });

    if (result.success) {
      logger.info(`Gitea-Repository erstellt: ${result.repository.fullName}`);
    }

    res.json(result);
  } catch (error) {
    logger.error('Fehler beim Erstellen des Repositories:', error);
    res.status(500).json({ success: false, error: error.message });
  }
});

/**
 * GET /api/gitea/repositories/:owner/:repo
 * Repository-Details abrufen
 */
router.get('/repositories/:owner/:repo', async (req, res) => {
  try {
    const { owner, repo } = req.params;
    const result = await giteaService.getRepository(owner, repo);
    res.json(result);
  } catch (error) {
    logger.error(`Fehler beim Abrufen des Repositories ${req.params.owner}/${req.params.repo}:`, error);
    res.status(500).json({ success: false, error: error.message });
  }
});

/**
 * DELETE /api/gitea/repositories/:owner/:repo
 * Repository löschen
 */
router.delete('/repositories/:owner/:repo', async (req, res) => {
  try {
    const { owner, repo } = req.params;
    const result = await giteaService.deleteRepository(owner, repo);

    if (result.success) {
      logger.info(`Gitea-Repository gelöscht: ${owner}/${repo}`);
    }

    res.json(result);
  } catch (error) {
    logger.error(`Fehler beim Löschen des Repositories ${req.params.owner}/${req.params.repo}:`, error);
    res.status(500).json({ success: false, error: error.message });
  }
});

/**
 * GET /api/gitea/repositories/:owner/:repo/branches
 * Branches eines Repositories abrufen
 */
router.get('/repositories/:owner/:repo/branches', async (req, res) => {
  try {
    const { owner, repo } = req.params;
    const result = await giteaService.getRepositoryBranches(owner, repo);
    res.json(result);
  } catch (error) {
    logger.error(`Fehler beim Abrufen der Branches für ${req.params.owner}/${req.params.repo}:`, error);
    res.status(500).json({ success: false, error: error.message });
  }
});

/**
 * GET /api/gitea/repositories/:owner/:repo/commits
 * Commits eines Repositories abrufen
 */
router.get('/repositories/:owner/:repo/commits', async (req, res) => {
  try {
    const { owner, repo } = req.params;
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 20;
    const branch = req.query.branch || '';

    const result = await giteaService.getRepositoryCommits(owner, repo, { page, limit, branch });
    res.json(result);
  } catch (error) {
    logger.error(`Fehler beim Abrufen der Commits für ${req.params.owner}/${req.params.repo}:`, error);
    res.status(500).json({ success: false, error: error.message });
  }
});

/**
 * GET /api/gitea/user
 * Aktuellen Gitea-Benutzer abrufen
 */
router.get('/user', async (req, res) => {
  try {
    const result = await giteaService.getCurrentUser();
    res.json(result);
  } catch (error) {
    logger.error('Fehler beim Abrufen des Gitea-Benutzers:', error);
    res.status(500).json({ success: false, error: error.message });
  }
});

module.exports = router;
