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

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

    if (!password) {
      return NextResponse.json(
        { success: false, error: 'Password is required' },
        { status: 400 }
      );
    }

    const settings = await AppSettings.findOne();
    if (!settings) {
      return NextResponse.json(
        { success: false, error: 'App not set up. Call /api/auth/setup first.' },
        { status: 404 }
      );
    }

    const isValid = await bcrypt.compare(password, settings.passwordHash);
    if (!isValid) {
      return NextResponse.json(
        { success: false, error: 'Invalid password' },
        { status: 401 }
      );
    }

    const secret = process.env.JWT_SECRET || settings.jwtSecret;
    const token = signToken({ role: 'user' }, secret);

    return NextResponse.json({ success: true, data: { token } });
  } catch (error: Error | unknown) {
    return NextResponse.json(
      { success: false, error: error instanceof Error ? error.message : 'Failed to verify password' },
      { status: 500 }
    );
  }
}
