import express from 'express';
import fetch from 'node-fetch';
import { emitMatchReportSubmitted } from '../services/socketService.js';

const router = express.Router();

// Cookie-Store für nuscore-Sessions
const cookieStore = new Map();

// Hilfsfunktion zum Extrahieren von Cookies aus Set-Cookie Headers
function extractCookies(setCookieHeaders) {
  const cookies = {};
  if (setCookieHeaders) {
    setCookieHeaders.forEach(cookie => {
      const [nameValue] = cookie.split(';');
      const [name, value] = nameValue.split('=');
      if (name && value) {
        cookies[name.trim()] = value.trim();
      }
    });
  }
  return cookies;
}

// Hilfsfunktion zum Formatieren von Cookies für Requests
function formatCookies(cookies) {
  return Object.entries(cookies)
    .map(([name, value]) => `${name}=${value}`)
    .join('; ');
}

// Meeting-Info API-Endpunkt
router.get('/meetinginfo/:code', async (req, res) => {
  const { code } = req.params;

  try {
    // Hole Cookies für diesen Code (falls vorhanden)
    const cookies = cookieStore.get(code) || {};
    
    const url = `https://ttde-apps.liga.nu/nuliga/rs/tt/2022/meetingentry/reports/${code}/meetinginfo`;
    
    const response = await fetch(url, {
      method: 'GET',
      headers: {
        'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:141.0) Gecko/20100101 Firefox/141.0',
        'Accept': 'application/json, text/plain, */*',
        'Accept-Language': 'de,en-US;q=0.7,en;q=0.3',
        'Accept-Encoding': 'gzip, deflate, br, zstd',
        'Referer': 'https://ttde-apps.liga.nu/nuliga/nuscore-tt/meetings-list',
        'Sec-Fetch-Dest': 'empty',
        'Sec-Fetch-Mode': 'cors',
        'Sec-Fetch-Site': 'same-origin',
        'Connection': 'keep-alive',
        ...(Object.keys(cookies).length > 0 && { 'Cookie': formatCookies(cookies) })
      }
    });

    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`);
    }

    const data = await response.json();
    
    // Speichere neue Cookies falls vorhanden
    const newCookies = extractCookies(response.headers.raw()['set-cookie']);
    if (Object.keys(newCookies).length > 0) {
      cookieStore.set(code, { ...cookies, ...newCookies });
    }

    // CORS-Header setzen
    res.set({
      'Content-Type': 'application/json; charset=utf-8',
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
      'Access-Control-Allow-Headers': 'Content-Type',
      'Cache-Control': 'no-cache, no-store, must-revalidate'
    });

    res.json(data);

  } catch (error) {
    console.error(`❌ Fehler beim Abrufen der Meeting-Info für Code ${code}:`, error);
    res.status(500).json({ 
      error: 'Fehler beim Abrufen der Meeting-Info', 
      details: error.message 
    });
  }
});

// Cookie-Initialisierung (für den ersten Request)
router.post('/init-cookies/:code', async (req, res) => {
  const { code } = req.params;

  try {
    // Erster Request an die nuscore-Seite um Cookies zu erhalten
    const response = await fetch(`https://ttde-apps.liga.nu/nuliga/nuscore-tt/meetings-list?code=${code}`, {
      method: 'GET',
      headers: {
        'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:141.0) Gecko/20100101 Firefox/141.0',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
        'Accept-Language': 'de,en-US;q=0.7,en;q=0.3',
        'Accept-Encoding': 'gzip, deflate, br, zstd',
        'Connection': 'keep-alive'
      }
    });

    // Extrahiere Cookies
    const cookies = extractCookies(response.headers.raw()['set-cookie']);
    if (Object.keys(cookies).length > 0) {
      cookieStore.set(code, cookies);
    }

    res.json({ 
      success: true, 
      cookies: Object.keys(cookies),
      message: `Cookies für Code ${code} initialisiert`
    });

  } catch (error) {
    console.error(`❌ Fehler bei Cookie-Initialisierung für Code ${code}:`, error);
    res.status(500).json({ 
      error: 'Fehler bei Cookie-Initialisierung', 
      details: error.message 
    });
  }
});

// Detaillierte Meeting-Daten API-Endpunkt
router.get('/meetingdetails/:uuid', async (req, res) => {
  const { uuid } = req.params;

  try {
    // Hole Cookies für diesen Code (falls vorhanden)
    const cookies = cookieStore.get(uuid) || {};
    
    const url = `https://ttde-apps.liga.nu/nuliga/rs/tt/2022/meetingentry/reports/${uuid}`;
    
    const response = await fetch(url, {
      method: 'GET',
      headers: {
        'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:141.0) Gecko/20100101 Firefox/141.0',
        'Accept': 'application/json, text/plain, */*',
        'Accept-Language': 'de,en-US;q=0.7,en;q=0.3',
        'Accept-Encoding': 'gzip, deflate, br, zstd',
        'Referer': 'https://ttde-apps.liga.nu/nuliga/nuscore-tt/meetings-list',
        'Sec-Fetch-Dest': 'empty',
        'Sec-Fetch-Mode': 'cors',
        'Sec-Fetch-Site': 'same-origin',
        'Connection': 'keep-alive',
        ...(Object.keys(cookies).length > 0 && { 'Cookie': formatCookies(cookies) })
      }
    });

    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`);
    }

    const data = await response.json();
    
    // Speichere neue Cookies falls vorhanden
    const newCookies = extractCookies(response.headers.raw()['set-cookie']);
    if (Object.keys(newCookies).length > 0) {
      cookieStore.set(uuid, { ...cookies, ...newCookies });
    }

    // CORS-Header setzen
    res.set({
      'Content-Type': 'application/json; charset=utf-8',
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
      'Access-Control-Allow-Headers': 'Content-Type',
      'Cache-Control': 'no-cache, no-store, must-revalidate'
    });

    res.json(data);

  } catch (error) {
    console.error(`❌ Fehler beim Abrufen der Meeting-Details für UUID ${uuid}:`, error);
    res.status(500).json({ 
      error: 'Fehler beim Abrufen der Meeting-Details', 
      details: error.message 
    });
  }
});

// Submit Meeting Report API-Endpunkt
router.put('/submit/:uuid', async (req, res) => {
  const { uuid } = req.params;
  const reportData = req.body;

  try {
    // Hole Cookies für diese UUID (falls vorhanden)
    // Versuche zuerst UUID, dann Code als Fallback
    let cookies = cookieStore.get(uuid) || {};
    
    // Falls keine Cookies für UUID vorhanden, versuche Code zu finden
    if (Object.keys(cookies).length === 0 && reportData.gameCode) {
      cookies = cookieStore.get(reportData.gameCode) || {};
    }
    
    const url = `https://ttde-apps.liga.nu/nuliga/rs/tt/2022/meetingentry/reports/${uuid}/submit`;
    
    const response = await fetch(url, {
      method: 'PUT',
      headers: {
        'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:141.0) Gecko/20100101 Firefox/141.0',
        'Accept': 'application/json, text/plain, */*',
        'Accept-Language': 'de,en-US;q=0.7,en;q=0.3',
        'Accept-Encoding': 'gzip, deflate, br, zstd',
        'Content-Type': 'application/json',
        'Referer': `https://ttde-apps.liga.nu/nuliga/nuscore-tt/meeting/${uuid}/report-clearance/review`,
        'Origin': 'https://ttde-apps.liga.nu',
        'Sec-Fetch-Dest': 'empty',
        'Sec-Fetch-Mode': 'cors',
        'Sec-Fetch-Site': 'same-origin',
        'Connection': 'keep-alive',
        ...(Object.keys(cookies).length > 0 && { 'Cookie': formatCookies(cookies) })
      },
      body: JSON.stringify(reportData)
    });

    const responseText = await response.text();
    let responseData;
    
    try {
      responseData = JSON.parse(responseText);
    } catch (e) {
      // Falls keine JSON-Antwort, verwende Text
      responseData = { message: responseText };
    }

    const resultState = responseData?.resultState;
    const validationErrors = Array.isArray(responseData?.validationErrors) ? responseData.validationErrors : [];

    if (!response.ok || resultState === 'VALIDATION_ERROR') {
      console.error(`❌ Submit fehlgeschlagen: HTTP ${response.status}`, responseData);
      return res.status(resultState === 'VALIDATION_ERROR' ? 422 : response.status).json({ 
        error: 'Fehler beim Absenden des Spielberichts', 
        details: responseData,
        status: resultState === 'VALIDATION_ERROR' ? 422 : response.status,
        statusText: response.statusText
      });
    }

    // Speichere neue Cookies falls vorhanden
    const newCookies = extractCookies(response.headers.raw()['set-cookie']);
    if (Object.keys(newCookies).length > 0) {
      cookieStore.set(uuid, { ...cookies, ...newCookies });
      if (reportData.gameCode) {
        cookieStore.set(reportData.gameCode, { ...cookies, ...newCookies });
      }
    }

    // CORS-Header setzen
    res.set({
      'Content-Type': 'application/json; charset=utf-8',
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Methods': 'GET, POST, PUT, OPTIONS',
      'Access-Control-Allow-Headers': 'Content-Type',
      'Cache-Control': 'no-cache, no-store, must-revalidate'
    });

    const clubId = reportData.clubId;
    const matchCode = reportData.gameCode || reportData.code;
    if (clubId && (matchCode || uuid)) {
      emitMatchReportSubmitted(clubId, matchCode || uuid, reportData);
    }

    res.json({
      success: true,
      data: responseData,
      message: 'Spielbericht erfolgreich abgesendet'
    });

  } catch (error) {
    console.error(`❌ Fehler beim Absenden des Spielberichts für UUID ${uuid}:`, error);
    res.status(500).json({ 
      error: 'Fehler beim Absenden des Spielberichts', 
      details: error.message 
    });
  }
});

// Nur Broadcast: aktueller Spielberichtsentwurf (z. B. Satzergebnisse) an andere Clients senden, ohne bei nuscore zu speichern
router.post('/broadcast-draft', (req, res) => {
  const { clubId, gameCode, matchData } = req.body || {};
  if (!clubId || !(gameCode ?? matchData?.gameCode ?? matchData?.code)) {
    return res.status(400).json({ error: 'clubId und gameCode erforderlich' });
  }
  const code = String(gameCode ?? matchData?.gameCode ?? matchData?.code ?? '');
  emitMatchReportSubmitted(clubId, code, matchData || null);
  res.json({ ok: true });
});

// Validate Meeting Report API-Endpunkt (für Zwischenspeicherung)
router.put('/validate/:uuid', async (req, res) => {
  const { uuid } = req.params;
  const reportData = req.body;

  try {
    // Hole Cookies für diese UUID (falls vorhanden)
    // Versuche zuerst UUID, dann Code als Fallback
    let cookies = cookieStore.get(uuid) || {};
    
    // Falls keine Cookies für UUID vorhanden, versuche Code zu finden
    if (Object.keys(cookies).length === 0 && reportData.gameCode) {
      cookies = cookieStore.get(reportData.gameCode) || {};
    }
    
    const url = `https://ttde-apps.liga.nu/nuliga/rs/tt/2022/meetingentry/reports/${uuid}/validate`;
    
    const response = await fetch(url, {
      method: 'PUT',
      headers: {
        'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:141.0) Gecko/20100101 Firefox/141.0',
        'Accept': 'application/json, text/plain, */*',
        'Accept-Language': 'de,en-US;q=0.7,en;q=0.3',
        'Accept-Encoding': 'gzip, deflate, br, zstd',
        'Content-Type': 'application/json',
        'Referer': `https://ttde-apps.liga.nu/nuliga/nuscore-tt/meeting/${uuid}/report-clearance/review`,
        'Origin': 'https://ttde-apps.liga.nu',
        'Sec-Fetch-Dest': 'empty',
        'Sec-Fetch-Mode': 'cors',
        'Sec-Fetch-Site': 'same-origin',
        'Connection': 'keep-alive',
        ...(Object.keys(cookies).length > 0 && { 'Cookie': formatCookies(cookies) })
      },
      body: JSON.stringify(reportData)
    });

    const responseText = await response.text();
    let responseData;
    
    try {
      responseData = JSON.parse(responseText);
    } catch (e) {
      // Falls keine JSON-Antwort, verwende Text
      responseData = { message: responseText };
    }

    // Speichere neue Cookies falls vorhanden
    const newCookies = extractCookies(response.headers.raw()['set-cookie']);
    if (Object.keys(newCookies).length > 0) {
      cookieStore.set(uuid, { ...cookies, ...newCookies });
      if (reportData.gameCode) {
        cookieStore.set(reportData.gameCode, { ...cookies, ...newCookies });
      }
    }

    // CORS-Header setzen
    res.set({
      'Content-Type': 'application/json; charset=utf-8',
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Methods': 'GET, POST, PUT, OPTIONS',
      'Access-Control-Allow-Headers': 'Content-Type',
      'Cache-Control': 'no-cache, no-store, must-revalidate'
    });

    // Validiere auch bei Fehlern (für Validierungsfehler)
    res.status(response.status).json(responseData);

  } catch (error) {
    console.error(`❌ Fehler beim Validieren des Spielberichts für UUID ${uuid}:`, error);
    res.status(500).json({ 
      error: 'Fehler beim Validieren des Spielberichts', 
      details: error.message 
    });
  }
});

export default router;
