import { NextRequest, NextResponse } from 'next/server';
import { mkdir, writeFile, readFile } from 'fs/promises';
import path from 'path';

const filePath = path.resolve(process.cwd(), 'data', 'contactMessages.json');

export async function POST(request: NextRequest) {
  try {
    await mkdir(path.dirname(filePath), { recursive: true });

    const body = await request.json();
    const { first_name, last_name, phone, email, message } = body;

    if (!first_name || !last_name || !phone || !email || !message) {
      return NextResponse.json(
        { error: 'مقدار تمامی فیلدها را پر کنید' },
        { status: 400 },
      );
    }

    let messages = [];
    try {
      const fileData = await readFile(filePath, 'utf-8');
      messages = JSON.parse(fileData);
    } catch {
      messages = [];
    }

    const newMessage = {
      first_name,
      last_name,
      phone,
      email,
      message,
      createdAt: new Date().toISOString(),
    };

    messages.push(newMessage);

    // Write updated messages back to file
    await writeFile(filePath, JSON.stringify(messages, null, 2), 'utf-8');

    return NextResponse.json({
      success: true,
      message: 'Your message has been received.',
    });
  } catch (error) {
    return NextResponse.json(
      { error, message: 'مشکلی پیش آمده.' },
      { status: 400 },
    );
  }
}
