/**
 * Ticket Digest Report API
 * POST /api/reports/ticket-digest — Generate and deliver a digest report
 *   Body: { period: 'daily' | 'weekly' | 'monthly', webhookIds?: number[] }
 * GET  /api/reports/ticket-digest — Get report history
 * GET  /api/reports/ticket-digest?preview=daily — Aggregate data only (no LLM, no delivery)
 */

import { NextRequest, NextResponse } from 'next/server';
import { getTicketDigestService, DigestPeriod } from '@/lib/services/ticket-digest-service';

const VALID_PERIODS: DigestPeriod[] = ['daily', 'weekly', 'monthly'];

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const period = body.period as DigestPeriod;

    if (!period || !VALID_PERIODS.includes(period)) {
      return NextResponse.json(
        { error: `Invalid period. Must be one of: ${VALID_PERIODS.join(', ')}` },
        { status: 400 }
      );
    }

    const service = getTicketDigestService();
    const result = await service.run(period, body.channelIds);

    return NextResponse.json({
      success: true,
      period,
      stats: result.stats.overview,
      noiseCount: result.stats.noise_candidates.length,
      analysisLength: result.analysis.length,
      deliveryResults: result.deliveryResults,
      processingTimeMs: result.processingTimeMs,
    });
  } catch (error) {
    const msg = error instanceof Error ? error.message : String(error);
    console.error('[TICKET-DIGEST API] Error:', msg);
    return NextResponse.json({ error: msg }, { status: 500 });
  }
}

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const preview = searchParams.get('preview') as DigestPeriod | null;

    const service = getTicketDigestService();

    if (preview && VALID_PERIODS.includes(preview)) {
      const stats = await service.aggregate(preview);
      return NextResponse.json({ stats });
    }

    // Return history + config + available notification channels
    const [history, config, channels] = await Promise.all([
      service.getHistory(20),
      service.getConfig(),
      service.getAvailableChannels(),
    ]);

    return NextResponse.json({ history, config, channels });
  } catch (error) {
    const msg = error instanceof Error ? error.message : String(error);
    console.error('[TICKET-DIGEST API] Error:', msg);
    return NextResponse.json({ error: msg }, { status: 500 });
  }
}
