import { NextResponse } from 'next/server';
import db from '@/lib/db';
import { getAdminSession } from '@/lib/auth';

// GET /api/admin/issues — fetch all issues with optional period filter for chart data
export async function GET(request: Request) {
  const session = await getAdminSession();
  if (!session) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }

  const { searchParams } = new URL(request.url);
  const period = searchParams.get('period'); // hourly, daily, weekly, monthly

  try {
    if (period) {
      // Return aggregated chart data for the specified period
      let dateFilter = '';
      const now = new Date();

      switch (period) {
        case 'hourly':
          // Last 24 hours, grouped by hour
          dateFilter = `AND created_at >= datetime('now', '-24 hours')`;
          break;
        case 'daily':
          // Last 30 days, grouped by day
          dateFilter = `AND created_at >= datetime('now', '-30 days')`;
          break;
        case 'weekly':
          // Last 12 weeks, grouped by week
          dateFilter = `AND created_at >= datetime('now', '-84 days')`;
          break;
        case 'monthly':
          // Last 12 months, grouped by month
          dateFilter = `AND created_at >= datetime('now', '-365 days')`;
          break;
        default:
          dateFilter = '';
      }

      // Get severity breakdown for the period
      const severityData = await db.query(
        `SELECT 
          CASE 
            WHEN created_at >= datetime('now', '-1 hour') THEN 'Last Hour'
            WHEN created_at >= datetime('now', '-24 hours') THEN 'Last 24h'
            WHEN created_at >= datetime('now', '-7 days') THEN 'Last 7 Days'
            ELSE 'Older'
          END as period_label,
          severity,
          COUNT(*) as count
        FROM issue_tracker
        WHERE 1=1 ${dateFilter ? dateFilter.replace('AND ', '') : ''}
        GROUP BY period_label, severity
        ORDER BY period_label, severity
      `) as any[];

      // Get total counts by severity
      const severityTotals = await db.query(
        `SELECT severity, COUNT(*) as count FROM issue_tracker GROUP BY severity`
      ) as any[];

      // Get counts by status
      const statusCounts = await db.query(
        `SELECT status, COUNT(*) as count FROM issue_tracker GROUP BY status`
      ) as any[];

      // Get counts by category
      const categoryCounts = await db.query(
        `SELECT category, COUNT(*) as count FROM issue_tracker GROUP BY category`
      ) as any[];

      return NextResponse.json({
        severityData: severityData || [],
        severityTotals: severityTotals || [],
        statusCounts: statusCounts || [],
        categoryCounts: categoryCounts || [],
        totalIssues: (severityTotals || []).reduce((sum: number, r: any) => sum + (r.count || 0), 0),
      });
    }

    // Return all issues (for the table)
    const issues = await db.query(
      'SELECT * FROM issue_tracker ORDER BY created_at DESC'
    ) as any[];

    return NextResponse.json({ issues: issues || [] });
  } catch (error: any) {
    console.error('[Issues API] Error:', error.message);
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}

// POST /api/admin/issues — create a new issue report
export async function POST(request: Request) {
  const session = await getAdminSession();
  if (!session) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }

  try {
    const body = await request.json();
    const { title, category, severity, description, steps_to_reproduce } = body;

    if (!title || !title.trim()) {
      return NextResponse.json({ error: 'Title is required' }, { status: 400 });
    }

    const result = await db.execute(
      `INSERT INTO issue_tracker (title, category, severity, description, steps_to_reproduce, created_at, updated_at)
       VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)`,
      [
        title.trim(),
        category || 'Other',
        severity || 'Low',
        description || '',
        steps_to_reproduce || '',
      ]
    );

    return NextResponse.json({
      success: true,
      id: result.lastInsertRowid,
    });
  } catch (error: any) {
    console.error('[Issues API] Error:', error.message);
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}

// PUT /api/admin/issues — update issue status
export async function PUT(request: Request) {
  const session = await getAdminSession();
  if (!session) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }

  try {
    const body = await request.json();
    const { id, status } = body;

    if (!id || !status) {
      return NextResponse.json({ error: 'id and status are required' }, { status: 400 });
    }

    const validStatuses = ['Open', 'In Progress', 'Resolved', 'Closed'];
    if (!validStatuses.includes(status)) {
      return NextResponse.json({ error: `Invalid status. Must be one of: ${validStatuses.join(', ')}` }, { status: 400 });
    }

    await db.execute(
      `UPDATE issue_tracker SET status = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?`,
      [status, id]
    );

    return NextResponse.json({ success: true });
  } catch (error: any) {
    console.error('[Issues API] Error:', error.message);
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}
