import { NextResponse } from 'next/server';
import dbConnect from '@/lib/db';
import Leader from '@/models/Leader';

export async function GET() {
  await dbConnect();
  try {
    const leaders = await (Leader as any).find({}).sort({ order: 1 });
    return NextResponse.json(leaders);
  } catch (error) {
    return NextResponse.json({ error: 'Failed to fetch leaders' }, { status: 500 });
  }
}

export async function POST(req: Request) {
  await dbConnect();
  try {
    const body = await req.json();
    
    const count = await (Leader as any).countDocuments();
    
    const leader = await (Leader as any).create({
      ...body,
      order: count,
      status: 'published'
    });
    
    return NextResponse.json(leader);
  } catch (error) {
    console.error(error);
    return NextResponse.json({ error: 'Failed to create leader' }, { status: 500 });
  }
}