/**
 * Public subscribe endpoint (PR-19, May 2026).
 *
 * POST /api/status/subscribe
 * Body: { email: string }
 *
 * Returns 200 with `{ ok: true }` REGARDLESS of whether the address
 * was already subscribed or whether a new row was created — this is
 * intentional, so an attacker can't enumerate which emails are on the
 * subscriber list. Invalid emails return 400. Rate limiting is applied
 * by the global middleware (100/min/IP).
 */
import { NextRequest, NextResponse } from 'next/server';
import { parseJsonBounded, BodyTooLargeError, BodyParseError } from '@/lib/api-helpers/parse-json';
import { StatusSubscriberService } from '@/lib/services/status-subscriber.service';

export const dynamic = 'force-dynamic';

export async function POST(req: NextRequest) {
    try {
        const body = await parseJsonBounded<{ email?: string }>(req, { maxBytes: 4 * 1024 });
        const email = typeof body.email === 'string' ? body.email : '';
        if (!email) {
            return NextResponse.json({ error: 'email is required' }, { status: 400 });
        }

        const service = new StatusSubscriberService();
        try {
            await service.requestSubscription(email);
        } catch (err) {
            const msg = err instanceof Error ? err.message : 'invalid email';
            if (/invalid email/i.test(msg)) {
                return NextResponse.json({ error: msg }, { status: 400 });
            }
            throw err;
        }

        // Same response for new + existing — don't leak.
        return NextResponse.json({
            ok: true,
            message: 'If that address is valid, a confirmation email is on its way.',
        });
    } catch (err: unknown) {
        if (err instanceof BodyTooLargeError) {
            return NextResponse.json({ error: err.message }, { status: 413 });
        }
        if (err instanceof BodyParseError) {
            return NextResponse.json({ error: err.message }, { status: 400 });
        }
        console.error('Subscribe error:', err);
        return NextResponse.json({ error: 'Internal error' }, { status: 500 });
    }
}
