import { NextResponse } from 'next/server';
import bcrypt from 'bcryptjs';
import crypto from 'crypto';
import connectToDatabase from '@/lib/mongodb';
import AppSettings from '@/models/AppSettings';

export async function POST(request: Request) {
  try {
    await connectToDatabase();
    const { password, setupKey } = await request.json();

    // Simple guard: require a setup key to prevent abuse
    const expectedKey = process.env.SETUP_KEY || 'setup-my-plan-app';
    if (setupKey !== expectedKey) {
      return NextResponse.json(
        { success: false, error: 'Invalid setup key' },
        { status: 403 }
      );
    }

    if (!password || password.length < 4) {
      return NextResponse.json(
        { success: false, error: 'Password must be at least 4 characters' },
        { status: 400 }
      );
    }

    const existingSettings = await AppSettings.findOne();
    const passwordHash = await bcrypt.hash(password, 12);
    const jwtSecret = process.env.JWT_SECRET || crypto.randomBytes(32).toString('hex');

    if (existingSettings) {
      existingSettings.passwordHash = passwordHash;
      existingSettings.jwtSecret = jwtSecret;
      await existingSettings.save();
    } else {
      await AppSettings.create({ passwordHash, jwtSecret });
    }

    return NextResponse.json({
      success: true,
      data: { message: 'Password set successfully. You can now login from the mobile app.' },
    });
  } catch (error: Error | unknown) {
    return NextResponse.json(
      { success: false, error: error instanceof Error ? error.message : 'Failed to setup app' },
      { status: 500 }
    );
  }
}
