/* eslint-disable -- temporary disable for development/testing purposes */

import { NextRequest, NextResponse } from 'next/server';
import { getDBConnection } from '@/lib/db'; // adjust path as needed


export async function POST(request: NextRequest) {
  const formData = await request.formData();

  const body: any = {};
  formData.forEach((value, key) => {
    body[key] = value;
  });

  const {
    referral_source,
    f_name,
    l_name,
    email,
    gender,
    address,
    mobile_number,
    password,
    lat,
    lng,
    age,
    dob,
    company_id,
    name,
    z_code
  } = body;

  if (!email || !mobile_number || !password || !company_id) {
    return NextResponse.json({ error: 'Required fields are missing' }, { status: 400 });
  }

 

  try {
    const connection = await getDBConnection();

    const [existing] = await connection.execute(
      'SELECT id FROM users WHERE email = ?',
      [email]
    );
    if ((existing as any[]).length > 0) {
      return NextResponse.json({ error: 'User already exists' }, { status: 409 });
    }

    await connection.execute(
      `INSERT INTO users 
        (name, referral_source, f_name, l_name, email, gender, address, mobile_number, role, password, age, dob, company_id, z_code, lat, lng)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
      [
        name || null,
        referral_source ?? null,
        f_name ?? null,
        l_name ?? null,
        email ?? null,
        gender ?? null,
        address ?? null,
        mobile_number ?? null,
        'user',
        password ?? null,
        age ?? null,
        dob ?? null,
        company_id ?? null,
        z_code ?? null,
        lat ?? null,
        lng ?? null
      ]
    );

    await connection.end();

    return NextResponse.json({ message: 'Patient created successfully' }, { status: 201 });
  } catch (error: any) {
    // console.error('Database Error:', error?.message || error);
    return NextResponse.json({ error: error?.message || 'Failed to create patient' }, { status: 500 });
  }
}
