import { eq } from 'drizzle-orm';
import { NextResponse } from 'next/server';
import { z } from 'zod';
import { db } from '@/db/drizzle';
import { user } from '@/db/schema';
import { auth } from '@/lib/auth';

const userUpdateSchema = z.object({
  name: z
    .string()
    .min(2, { message: 'Name must be at least 2 characters.' })
    .optional(),
  email: z.string().email({ message: 'Invalid email address.' }).optional(),
  image: z.string().optional(),
  phone: z.string().optional(),
  marital: z
    .enum([
      'single',
      'married',
      'Widowed',
      'Divorced',
      'Separated',
      'Engaged',
      'Complicated',
    ])
    .optional(),
  state: z.string().optional(),
  gender: z.enum(['male', 'female']).optional(),
  address: z.string().optional(),
  aboutMe: z.string().optional(),
  dob: z.string().optional(),
  weddingAnniversary: z.string().optional(),
  callerSquad: z.boolean().optional(),
  userTitle: z
    .enum(['brother', 'sister', 'deacon', 'deaconess', 'pastor', 'elder'])
    .optional(),
});

export async function PUT(
  req: Request,
  { params }: { params: { id: string } }
) {
  try {
    const userId = params.id;
    const body = await req.json();

    const session = await auth.api.getSession({
      headers: req.headers,
    });

    if (!session || session.user.id !== userId) {
      return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
    }

    if (!userId) {
      return NextResponse.json(
        { error: 'User ID is required' },
        { status: 400 }
      );
    }

    const validation = userUpdateSchema.safeParse(body);

    if (!validation.success) {
      return NextResponse.json(
        { errors: validation.error.flatten().fieldErrors },
        { status: 400 }
      );
    }

    const updateData = validation.data;

    if (Object.keys(updateData).length === 0) {
      return NextResponse.json(
        { error: 'No update data provided' },
        { status: 400 }
      );
    }

    const updateduser = await db
      .update(user)
      .set(updateData)
      .where(eq(user.id, userId))
      .execute();

    if (updateduser.length === 0) {
      return NextResponse.json({ error: 'User not found' }, { status: 404 });
    }

    return NextResponse.json(updateduser[0], { status: 200 });
  } catch (error) {
    console.error('Error updating user:', error);
    return NextResponse.json(
      { error: 'Internal Server Error' },
      { status: 500 }
    );
  }
}
