import { NextRequest, NextResponse } from 'next/server';
import { cookies } from 'next/headers';
import bcrypt from 'bcryptjs';
import { db } from '@/lib/db';
import { getAuthCookieOptions } from '@/lib/cookieConfig';

/**
 * POST /api/newsletter/admin-login
 * Simple admin login for newsletter management (no CSRF required)
 */
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { email, password } = body;

    // Validate input
    if (!email || !password) {
      return NextResponse.json(
        { error: 'Email and password are required' },
        { status: 400 }
      );
    }

    // SECURITY: Only allow support@qrmaster.net to access newsletter admin
    const ALLOWED_ADMIN_EMAIL = 'support@qrmaster.net';
    const ALLOWED_ADMIN_PASSWORD = 'Timo.16092005';

    if (email.toLowerCase() !== ALLOWED_ADMIN_EMAIL) {
      return NextResponse.json(
        { error: 'Access denied. Only authorized accounts can access this area.' },
        { status: 403 }
      );
    }

    // Verify password with hardcoded value
    if (password !== ALLOWED_ADMIN_PASSWORD) {
      return NextResponse.json(
        { error: 'Invalid credentials' },
        { status: 401 }
      );
    }

    // Set auth cookie with a simple session identifier
    const response = NextResponse.json({
      success: true,
      message: 'Login successful',
    });

    response.cookies.set('newsletter-admin', 'authenticated', getAuthCookieOptions());

    return response;
  } catch (error) {
    console.error('Newsletter admin login error:', error);
    return NextResponse.json(
      { error: 'Login failed. Please try again.' },
      { status: 500 }
    );
  }
}
