import { eq } from 'drizzle-orm';
import { headers } from 'next/headers';
import { NextResponse } from 'next/server';
import { db } from '@/db/drizzle';
import { about } from '@/db/schema';
import { auth } from '@/lib/auth';
import { handleImageUpload } from '@/lib/image-upload';

export async function GET(req: Request) {
  const session = await auth.api.getSession({
    headers: req.headers,
  });

  // if (!session?.user || session.user.role !== 'admin') {
  if (!session?.user) {
    return NextResponse.json({ message: 'Unauthorized' }, { status: 401 });
  }

  try {
    const aboutData = await db.select().from(about).limit(1);
    return NextResponse.json(aboutData[0] || null);
  } catch (error) {
    console.error('Error fetching about data:', error);
    return NextResponse.json(
      { message: 'Failed to fetch about data' },
      { status: 500 }
    );
  }
}

export async function POST(req: Request) {
  const session = await auth.api.getSession({
    headers: req.headers,
  });

  if (!session?.user || session.user.role !== 'admin') {
    return NextResponse.json({ message: 'Unauthorized' }, { status: 401 });
  }

  try {
    const formData = await req.formData();

    const title = formData.get('title')?.toString() ?? '';
    const aboutContent = formData.get('about')?.toString() ?? '';
    const history = formData.get('history')?.toString() ?? '';
    const achievement = formData.get('achievement')?.toString() ?? '';
    const purpose = formData.get('purpose')?.toString() ?? '';
    const vision = formData.get('vision')?.toString() ?? '';
    const mission = formData.get('mission')?.toString() ?? '';
    const phone = formData.get('phone')?.toString() ?? '';
    const email = formData.get('email')?.toString() ?? '';
    const address = formData.get('address')?.toString() ?? '';
    const facebook = formData.get('facebook')?.toString() ?? '';
    const twitter = formData.get('twitter')?.toString() ?? '';
    const instagram = formData.get('instagram')?.toString() ?? '';
    const linkedin = formData.get('linkedin')?.toString() ?? '';
    const imageFile = formData.get('image_file') as File | null;
    const logoFile = formData.get('logo_file') as File | null;
    const logo2File = formData.get('logo2_file') as File | null;

    const imagePath = await handleImageUpload(imageFile);
    const logoPath = await handleImageUpload(logoFile);
    const logo2Path = await handleImageUpload(logo2File);

    const newAbout = await db.insert(about).values({
      id: crypto.randomUUID(),
      title,
      about: aboutContent,
      history,
      achievement,
      purpose,
      vision,
      mission,
      phone,
      email,
      address,
      facebook,
      twitter,
      instagram,
      linkedin,
      image: imagePath,
      logo: logoPath,
      logo2: logo2Path,
      createdAt: new Date(),
      updatedAt: new Date(),
    });

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

export async function PUT(req: Request) {
  const session = await auth.api.getSession({
    headers: req.headers,
  });

  if (!session?.user || session.user.role !== 'admin') {
    return NextResponse.json({ message: 'Unauthorized' }, { status: 401 });
  }

  try {
    const formData = await req.formData();

    const title = formData.get('title')?.toString() ?? '';
    const aboutContent = formData.get('about')?.toString() ?? '';
    const history = formData.get('history')?.toString() ?? '';
    const achievement = formData.get('achievement')?.toString() ?? '';
    const purpose = formData.get('purpose')?.toString() ?? '';
    const vision = formData.get('vision')?.toString() ?? '';
    const mission = formData.get('mission')?.toString() ?? '';
    const phone = formData.get('phone')?.toString() ?? '';
    const email = formData.get('email')?.toString() ?? '';
    const address = formData.get('address')?.toString() ?? '';
    const facebook = formData.get('facebook')?.toString() ?? '';
    const twitter = formData.get('twitter')?.toString() ?? '';
    const instagram = formData.get('instagram')?.toString() ?? '';
    const linkedin = formData.get('linkedin')?.toString() ?? '';
    const imageFile = formData.get('image_file') as File | null;
    const logoFile = formData.get('logo_file') as File | null;
    const logo2File = formData.get('logo2_file') as File | null;
    const existingImage = formData.get('existing_image')?.toString() ?? null;
    const existingLogo = formData.get('existing_logo')?.toString() ?? null;
    const existingLogo2 = formData.get('existing_logo2')?.toString() ?? null;

    const imagePath = await handleImageUpload(imageFile, existingImage);
    const logoPath = await handleImageUpload(logoFile, existingLogo);
    const logo2Path = await handleImageUpload(logo2File, existingLogo2);

    const updatedAbout = await db
      .update(about)
      .set({
        title,
        about: aboutContent,
        history,
        achievement,
        purpose,
        vision,
        mission,
        phone,
        email,
        address,
        facebook,
        twitter,
        instagram,
        linkedin,
        image: imagePath,
        logo: logoPath,
        logo2: logo2Path,
        updatedAt: new Date(),
      })
      .where(eq(about.id, '1')); // Assuming a single entry with ID '1'

    return NextResponse.json(updatedAbout, { status: 200 });
  } catch (error: any) {
    console.error('Error updating about data:', error);
    return NextResponse.json(
      { message: error.message || 'Failed to update about data' },
      { status: 500 }
    );
  }
}
