/**
 * Data Retention API
 *
 * Ermöglicht manuelles Auslösen von Retention-Jobs.
 * Nur für Super-Admins zugänglich.
 */

import { NextRequest, NextResponse } from 'next/server'
import { getPayload } from 'payload'
import config from '@payload-config'
import {
  enqueueFullRetention,
  enqueueCollectionCleanup,
  enqueueMediaOrphanCleanup,
  getRetentionJobStatus,
} from '@/lib/queue/jobs/retention-job'
import { retentionPolicies, getCutoffDate, mediaOrphanConfig } from '@/lib/retention'

/**
 * GET /api/retention
 *
 * Gibt die aktuelle Retention-Konfiguration und Job-Status zurück.
 */
export async function GET(request: NextRequest): Promise<NextResponse> {
  try {
    const payload = await getPayload({ config })

    // Auth-Check
    const authHeader = request.headers.get('authorization')
    const cookieHeader = request.headers.get('cookie')

    let user = null

    // Versuche Auth über Header oder Cookie
    if (authHeader?.startsWith('Bearer ') || cookieHeader) {
      try {
        const result = await payload.auth({
          headers: request.headers,
        })
        user = result.user
      } catch {
        // Auth fehlgeschlagen
      }
    }

    if (!user) {
      return NextResponse.json({ error: 'Authentication required' }, { status: 401 })
    }

    // Nur Super-Admins
    if (!user.isSuperAdmin) {
      return NextResponse.json({ error: 'Super admin access required' }, { status: 403 })
    }

    // Job-Status abfragen falls jobId angegeben
    const jobId = request.nextUrl.searchParams.get('jobId')
    if (jobId) {
      const status = await getRetentionJobStatus(jobId)
      if (!status) {
        return NextResponse.json({ error: 'Job not found' }, { status: 404 })
      }
      return NextResponse.json(status)
    }

    // Konfiguration zurückgeben
    return NextResponse.json({
      policies: retentionPolicies.map((p) => ({
        name: p.name,
        collection: p.collection,
        retentionDays: p.retentionDays,
        dateField: p.dateField,
        description: p.description,
      })),
      mediaOrphan: {
        minAgeDays: mediaOrphanConfig.minAgeDays,
        referencingCollections: mediaOrphanConfig.referencingCollections,
      },
      environment: {
        RETENTION_EMAIL_LOGS_DAYS: process.env.RETENTION_EMAIL_LOGS_DAYS || '90',
        RETENTION_AUDIT_LOGS_DAYS: process.env.RETENTION_AUDIT_LOGS_DAYS || '90',
        RETENTION_CONSENT_LOGS_DAYS: process.env.RETENTION_CONSENT_LOGS_DAYS || '1095',
        RETENTION_MEDIA_ORPHAN_MIN_AGE_DAYS: process.env.RETENTION_MEDIA_ORPHAN_MIN_AGE_DAYS || '30',
        RETENTION_CRON_SCHEDULE: process.env.RETENTION_CRON_SCHEDULE || '0 3 * * *',
      },
    })
  } catch (error) {
    console.error('[RetentionAPI] Error:', error)
    return NextResponse.json(
      { error: error instanceof Error ? error.message : 'Internal server error' },
      { status: 500 }
    )
  }
}

/**
 * POST /api/retention
 *
 * Löst einen Retention-Job aus.
 *
 * Body:
 * - type: 'full' | 'collection' | 'media-orphans'
 * - collection?: string (für type='collection')
 */
export async function POST(request: NextRequest): Promise<NextResponse> {
  try {
    const payload = await getPayload({ config })

    // Auth-Check
    const authHeader = request.headers.get('authorization')
    const cookieHeader = request.headers.get('cookie')

    let user = null

    if (authHeader?.startsWith('Bearer ') || cookieHeader) {
      try {
        const result = await payload.auth({
          headers: request.headers,
        })
        user = result.user
      } catch {
        // Auth fehlgeschlagen
      }
    }

    if (!user) {
      return NextResponse.json({ error: 'Authentication required' }, { status: 401 })
    }

    // Nur Super-Admins
    if (!user.isSuperAdmin) {
      return NextResponse.json({ error: 'Super admin access required' }, { status: 403 })
    }

    // Body parsen
    const body = await request.json().catch(() => ({}))
    const { type, collection } = body as { type?: string; collection?: string }

    if (!type) {
      return NextResponse.json({ error: 'Type is required' }, { status: 400 })
    }

    let job

    switch (type) {
      case 'full':
        job = await enqueueFullRetention(user.email)
        break

      case 'collection':
        if (!collection) {
          return NextResponse.json({ error: 'Collection is required for type=collection' }, { status: 400 })
        }

        // Prüfe ob Collection in Policies definiert
        const policy = retentionPolicies.find((p) => p.collection === collection)
        if (!policy) {
          return NextResponse.json(
            {
              error: `Collection '${collection}' not found in retention policies`,
              availableCollections: retentionPolicies.map((p) => p.collection),
            },
            { status: 400 }
          )
        }

        const cutoff = getCutoffDate(policy.retentionDays)
        job = await enqueueCollectionCleanup(collection, cutoff, {
          batchSize: policy.batchSize,
          dateField: policy.dateField,
          triggeredBy: user.email,
        })
        break

      case 'media-orphans':
        job = await enqueueMediaOrphanCleanup({
          triggeredBy: user.email,
        })
        break

      default:
        return NextResponse.json(
          {
            error: `Invalid type: ${type}`,
            validTypes: ['full', 'collection', 'media-orphans'],
          },
          { status: 400 }
        )
    }

    return NextResponse.json({
      success: true,
      jobId: job.id,
      type,
      collection,
      message: `Retention job queued successfully. Use GET /api/retention?jobId=${job.id} to check status.`,
    })
  } catch (error) {
    console.error('[RetentionAPI] Error:', error)
    return NextResponse.json(
      { error: error instanceof Error ? error.message : 'Internal server error' },
      { status: 500 }
    )
  }
}
