import { NextRequest, NextResponse } from 'next/server';
import { jeffWelcomeEmail } from '@/lib/adops/emailTemplates';
import { sendAdOpsEmail } from '@/lib/adops/adOpsEmailSender';
import { createClient } from '@/lib/supabase/server';

async function requireAdmin(request: NextRequest) {
  const supabase = await createClient();
  const { data: { user } } = await supabase.auth.getUser();
  if (!user) return null;
  const { data: profile } = await supabase
    .from('user_profiles')
    .select('role')
    .eq('id', user.id)
    .single();
  if (!profile || !['administrator', 'admin'].includes(profile.role)) return null;
  return user;
}

// POST /api/adops/onboard — send Jeff's welcome email
export async function POST(request: NextRequest) {
  const user = await requireAdmin(request);
  if (!user) return NextResponse.json({ error: 'Not found' }, { status: 404 });

  const welcome = jeffWelcomeEmail();
  const result = await sendAdOpsEmail({
    to: welcome.to,
    cc: [welcome.cc],
    subject: welcome.subject,
    html: welcome.html,
    alwaysCcRyan: false,
  });

  return NextResponse.json({ success: result.success, error: result.error });
}
