import { NextResponse } from 'next/server';
import dbConnect from '@/lib/db';
import User from '@/models/User';
import { verifyAuth, hashPassword } from '@/lib/auth';
import { cookies } from 'next/headers';

export async function GET() {
  await dbConnect();
  const token = (await cookies()).get('auth_token')?.value;
  if (!token) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

  try {
    const payload: any = await verifyAuth(token);
    const user = await (User as any).findById(payload.userId).select('-password -securityAnswer1 -securityAnswer2');
    return NextResponse.json(user);
  } catch (e) {
    return NextResponse.json({ error: 'Error fetching profile' }, { status: 500 });
  }
}

export async function PUT(req: Request) {
  await dbConnect();
  const token = (await cookies()).get('auth_token')?.value;
  if (!token) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

  try {
    const payload: any = await verifyAuth(token);
    const body = await req.json();
    const updateData: any = { 
      name: body.name, 
      phone: body.phone, 
      email: body.email 
    };

    // Update Security Questions if provided
    if (body.securityQuestion1 && body.securityAnswer1) {
      updateData.securityQuestion1 = body.securityQuestion1;
      updateData.securityAnswer1 = await hashPassword(body.securityAnswer1.toLowerCase().trim());
    }
    if (body.securityQuestion2 && body.securityAnswer2) {
      updateData.securityQuestion2 = body.securityQuestion2;
      updateData.securityAnswer2 = await hashPassword(body.securityAnswer2.toLowerCase().trim());
    }

    // Update Password if provided
    if (body.password) {
      updateData.password = await hashPassword(body.password);
    }

    const user = await (User as any).findByIdAndUpdate(payload.userId, updateData, { new: true });
    return NextResponse.json({ success: true });
  } catch (e) {
    console.error(e);
    return NextResponse.json({ error: 'Error updating profile' }, { status: 500 });
  }
}
