import { NextResponse } from 'next/server';
import { db } from '@/db/drizzle';
import { job } from '@/db/schema';

export async function GET() {
  try {
    const jobs = await db.select().from(job);
    return NextResponse.json(jobs);
  } catch (error) {
    console.error('Error fetching jobs:', error);
    return NextResponse.json(
      { message: 'Failed to fetch jobs' },
      { status: 500 }
    );
  }
}

export async function POST(req: Request) {
  try {
    const formData = await req.formData();

    const title = formData.get('title')?.toString() ?? '';
    const location = formData.get('location')?.toString() ?? '';
    const type = formData.get('type')?.toString() ?? '';
    const department = formData.get('department')?.toString() ?? '';
    const description = formData.get('description')?.toString() ?? '';
    const responsibilities = formData.get('responsibilities')?.toString() ?? '';
    const requirements = formData.get('requirements')?.toString() ?? '';
    const slug = formData.get('slug')?.toString() ?? '';
    const status = formData.get('status')?.toString() === 'true';
    const closed = formData.get('closed')?.toString() === 'true';

    // Validate required fields
    if (!title || !slug) {
      return NextResponse.json(
        { message: 'Title and slug are required' },
        { status: 400 }
      );
    }

    const newJob = await db.insert(job).values({
      id: crypto.randomUUID(),
      title,
      location,
      type,
      department,
      description,
      responsibilities,
      requirements,
      slug,
      status,
      closed,
      createdAt: new Date(),
      updatedAt: new Date(),
    });

    return NextResponse.json(newJob, { status: 201 });
  } catch (error: any) {
    console.error('Error creating job:', error);
    return NextResponse.json(
      { message: error.message || 'Failed to create job' },
      { status: 500 }
    );
  }
}
