/**
 * API Route: Cookie Banner Embed Code
 *
 * GET - Generiert den Embed-Code fuer den Cookie Banner
 */

import { NextRequest, NextResponse } from 'next/server'
import { CookieBannerConfig } from '@/lib/sdk/einwilligungen/types'
import {
  generateCookieBannerConfig,
  generateEmbedCode,
} from '@/lib/sdk/einwilligungen/generator/cookie-banner'
import { PREDEFINED_DATA_POINTS } from '@/lib/sdk/einwilligungen/catalog/loader'

const BACKEND_URL = process.env.BACKEND_URL || 'http://backend-compliance:8002'
const DEFAULT_TENANT_ID = process.env.DEFAULT_TENANT_ID || '9282a473-5c95-4b3a-bf78-0ecc0ec71d3e'

/**
 * GET /api/sdk/v1/einwilligungen/cookie-banner/embed-code
 *
 * Generiert den Embed-Code fuer den Cookie Banner (DB-backed)
 *
 * Query Parameters:
 * - privacyPolicyUrl: string - URL zur Datenschutzerklaerung (default: /datenschutz)
 * - format: 'combined' | 'separate' - Ausgabeformat (default: combined)
 */
export async function GET(request: NextRequest) {
  try {
    const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
    const clientTenantId = request.headers.get('X-Tenant-ID') || request.headers.get('x-tenant-id')
    const tenantId = (clientTenantId && uuidRegex.test(clientTenantId)) ? clientTenantId : DEFAULT_TENANT_ID

    const { searchParams } = new URL(request.url)
    const privacyPolicyUrl = searchParams.get('privacyPolicyUrl') || '/datenschutz'
    const format = searchParams.get('format') || 'combined'

    // Lade Konfiguration aus DB (Backend), fallback auf generierte Standardkonfiguration
    let config: CookieBannerConfig
    try {
      const configRes = await fetch(
        `${BACKEND_URL}/api/compliance/einwilligungen/cookies?tenant_id=${tenantId}`,
        { signal: AbortSignal.timeout(5000) }
      )
      if (configRes.ok) {
        const configData = await configRes.json()
        config = generateCookieBannerConfig(tenantId, PREDEFINED_DATA_POINTS)
        if (configData.config && Object.keys(configData.config).length > 0) {
          const saved = configData.config
          config = {
            ...config,
            styling: { ...config.styling, ...(saved.styling || {}) },
            texts: { ...config.texts, ...(saved.banner_texts || saved.texts || {}) },
          }
        }
      } else {
        config = generateCookieBannerConfig(tenantId, PREDEFINED_DATA_POINTS)
      }
    } catch {
      config = generateCookieBannerConfig(tenantId, PREDEFINED_DATA_POINTS)
    }

    // Generiere Embed-Code
    const embedCode = generateEmbedCode(config, privacyPolicyUrl)

    if (format === 'separate') {
      // Separate Dateien zurueckgeben
      return NextResponse.json({
        html: embedCode.html,
        css: embedCode.css,
        js: embedCode.js,
        scriptTag: embedCode.scriptTag,
        instructions: {
          de: `
Fuegen Sie den folgenden Code in Ihre Website ein:

1. CSS in den <head>-Bereich:
   <style>${embedCode.css}</style>

2. HTML vor dem schliessenden </body>-Tag:
   ${embedCode.html}

3. JavaScript vor dem schliessenden </body>-Tag:
   <script>${embedCode.js}</script>

Alternativ koennen Sie die Dateien separat einbinden:
- /cookie-banner.css
- /cookie-banner.js
`,
          en: `
Add the following code to your website:

1. CSS in the <head> section:
   <style>${embedCode.css}</style>

2. HTML before the closing </body> tag:
   ${embedCode.html}

3. JavaScript before the closing </body> tag:
   <script>${embedCode.js}</script>

Alternatively, you can include the files separately:
- /cookie-banner.css
- /cookie-banner.js
`,
        },
      })
    }

    // Combined: Alles in einem HTML-Block
    const combinedCode = `
<!-- Cookie Banner - Start -->
<style>
${embedCode.css}
</style>

${embedCode.html}

<script>
${embedCode.js}
</script>
<!-- Cookie Banner - End -->
`.trim()

    return NextResponse.json({
      embed_code: combinedCode,
      embedCode: combinedCode,
      scriptTag: embedCode.scriptTag,
      config: {
        tenantId: config.tenantId,
        categories: config.categories.map((c) => ({
          id: c.id,
          name: c.name,
          isRequired: c.isRequired,
          defaultEnabled: c.defaultEnabled,
        })),
        styling: config.styling,
      },
      instructions: {
        de: `Fuegen Sie den folgenden Code vor dem schliessenden </body>-Tag Ihrer Website ein.`,
        en: `Add the following code before the closing </body> tag of your website.`,
      },
    })
  } catch (error) {
    console.error('Error generating embed code:', error)
    return NextResponse.json(
      { error: 'Failed to generate embed code' },
      { status: 500 }
    )
  }
}

/**
 * POST /api/sdk/v1/einwilligungen/cookie-banner/embed-code
 *
 * Generiert Embed-Code mit benutzerdefinierten Optionen
 */
export async function POST(request: NextRequest) {
  try {
    const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
    const clientTenantId = request.headers.get('X-Tenant-ID') || request.headers.get('x-tenant-id')
    const tenantId = (clientTenantId && uuidRegex.test(clientTenantId)) ? clientTenantId : DEFAULT_TENANT_ID

    const body = await request.json()
    const {
      privacyPolicyUrl = '/datenschutz',
      styling,
      texts,
      language = 'de',
    } = body

    // Erstelle Konfiguration mit optionalen Overrides
    let config: CookieBannerConfig = generateCookieBannerConfig(tenantId, PREDEFINED_DATA_POINTS, texts, styling)
    if (styling) {
      config = { ...config, styling: { ...config.styling, ...styling } }
    }
    if (texts) {
      config = { ...config, texts: { ...config.texts, ...texts } }
    }

    const embedCode = generateEmbedCode(config, privacyPolicyUrl)

    // Generiere Preview HTML
    const previewHtml = `
<!DOCTYPE html>
<html lang="${language}">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Cookie Banner Preview</title>
  <style>
    body {
      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
      background: #f1f5f9;
      min-height: 100vh;
      margin: 0;
      padding: 20px;
    }
    .preview-content {
      max-width: 800px;
      margin: 0 auto;
      padding: 40px;
      background: white;
      border-radius: 12px;
      box-shadow: 0 4px 12px rgba(0,0,0,0.1);
    }
    h1 { color: #1e293b; }
    p { color: #64748b; line-height: 1.6; }
    ${embedCode.css}
  </style>
</head>
<body>
  <div class="preview-content">
    <h1>Cookie Banner Preview</h1>
    <p>Dies ist eine Vorschau des Cookie Banners. In der produktiven Umgebung wird der Banner auf Ihrer Website angezeigt.</p>
  </div>

  ${embedCode.html}

  <script>
    ${embedCode.js}
    // Force show banner for preview
    setTimeout(() => {
      document.getElementById('cookieBanner')?.classList.add('active');
      document.getElementById('cookieBannerOverlay')?.classList.add('active');
    }, 100);
  </script>
</body>
</html>
`.trim()

    return NextResponse.json({
      embedCode: {
        html: embedCode.html,
        css: embedCode.css,
        js: embedCode.js,
        scriptTag: embedCode.scriptTag,
      },
      previewHtml,
      config: {
        tenantId: config.tenantId,
        categories: config.categories.length,
        styling: config.styling,
      },
    })
  } catch (error) {
    console.error('Error generating custom embed code:', error)
    return NextResponse.json(
      { error: 'Failed to generate embed code' },
      { status: 500 }
    )
  }
}
