import { NextRequest, NextResponse } from 'next/server';
import { createClient } from '@/lib/supabase/server';
import { createAdminClient } from '@/lib/supabase/admin';
import { badRequest, logApiError, readJsonBody } from '@/lib/api/security';

const SUPER_ADMIN_EMAIL = 'schmidtmartin930@gmail.com';

async function checkAuth() {
  const supabase = await createClient();
  const { data: { user } } = await supabase.auth.getUser();
  if (!user || user.email !== SUPER_ADMIN_EMAIL) return null;
  return user;
}

/** GET /api/admin/codes — list all promo codes */
export async function GET() {
  const user = await checkAuth();
  if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

  try {
    const admin = createAdminClient();
    const { data, error } = await admin
      .from('promo_codes')
      .select('*')
      .order('created_at', { ascending: false });
    if (error) throw error;
    return NextResponse.json(data ?? []);
  } catch (error) {
    logApiError('Admin codes GET error', error);
    return NextResponse.json({ error: 'Codes konnten nicht geladen werden' }, { status: 500 });
  }
}

/** POST /api/admin/codes — create a promo code */
export async function POST(req: NextRequest) {
  const user = await checkAuth();
  if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

  const body = await readJsonBody<{
    code: string;
    plan: string;
    duration_months: number;
    max_uses: number;
    expires_at?: string | null;
    note?: string;
  }>(req);
  if (!body) return badRequest('Ungültige Anfrage');

  const { code, plan, duration_months, max_uses, expires_at, note } = body;
  if (
    typeof code !== 'string' || typeof plan !== 'string' ||
    typeof duration_months !== 'number' || typeof max_uses !== 'number' ||
    !code.trim() || !plan.trim() || duration_months < 1 || max_uses < 1
  ) {
    return NextResponse.json({ error: 'Fehlende Felder' }, { status: 400 });
  }

  try {
    const admin = createAdminClient();
    const { data, error } = await admin
      .from('promo_codes')
      .insert({
        code: code.toUpperCase().trim(),
        plan,
        duration_months,
        max_uses,
        expires_at: expires_at ?? null,
        note: note ?? null,
        created_by: user.id,
      })
      .select()
      .single();

    if (error) {
      if (error.code === '23505') {
        return NextResponse.json({ error: 'Code existiert bereits' }, { status: 409 });
      }
      throw error;
    }
    return NextResponse.json(data);
  } catch (error) {
    logApiError('Admin codes POST error', error);
    return NextResponse.json({ error: 'Code konnte nicht erstellt werden' }, { status: 500 });
  }
}

/** PATCH /api/admin/codes — toggle active */
export async function PATCH(req: NextRequest) {
  const user = await checkAuth();
  if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

  const body = await readJsonBody<{ id: string; active: boolean }>(req);
  if (!body) return badRequest('Ungültige Anfrage');
  const { id, active } = body;
  if (!id) return NextResponse.json({ error: 'Missing id' }, { status: 400 });
  if (typeof active !== 'boolean') return NextResponse.json({ error: 'Invalid active value' }, { status: 400 });

  try {
    const admin = createAdminClient();
    const { error } = await admin
      .from('promo_codes')
      .update({ active })
      .eq('id', id);
    if (error) throw error;
    return NextResponse.json({ ok: true });
  } catch (error) {
    logApiError('Admin codes PATCH error', error);
    return NextResponse.json({ error: 'Code konnte nicht aktualisiert werden' }, { status: 500 });
  }
}

/** DELETE /api/admin/codes — permanently delete a code */
export async function DELETE(req: NextRequest) {
  const user = await checkAuth();
  if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

  const body = await readJsonBody<{ id: string }>(req);
  if (!body) return badRequest('Ungültige Anfrage');
  const { id } = body;
  if (!id) return NextResponse.json({ error: 'Missing id' }, { status: 400 });

  try {
    const admin = createAdminClient();
    const { error } = await admin
      .from('promo_codes')
      .delete()
      .eq('id', id);
    if (error) throw error;
    return NextResponse.json({ ok: true });
  } catch (error) {
    logApiError('Admin codes DELETE error', error);
    return NextResponse.json({ error: 'Code konnte nicht gelöscht werden' }, { status: 500 });
  }
}
