/**
 * Manual customer marketing opt-out toggle. Used by the CRM detail panel —
 * the operator can flip a customer in or out of marketing without waiting
 * for an email link click or a WhatsApp STOP keyword.
 *
 * POST   → opt out
 * DELETE → opt back in
 */

import { NextResponse } from 'next/server';
import { withErrorHandler, RouteContext } from '@server/middleware/withErrorHandler';
import { withAuth, AuthedRequest } from '@server/middleware/withAuth';
import { db } from '@server/db/drizzle';
import { sql } from 'drizzle-orm';
import { ValidationError } from '@server/errors';

async function ensureCustomerExists(id: string, restaurantId: string): Promise<void> {
  const { rows } = await db.execute(sql`
    SELECT 1 FROM customers WHERE id = ${id} AND restaurant_id = ${restaurantId} LIMIT 1
  `);
  if (rows.length === 0) throw new ValidationError('Customer not found');
}

export const POST = withErrorHandler(
  withAuth(async (req: AuthedRequest, ctx: RouteContext) => {
    const restaurantId = req.session.restaurantId!;
    const { id } = await ctx.params;
    await ensureCustomerExists(id, restaurantId);

    let reason: string | null = null;
    try {
      const body = await req.json();
      if (body && typeof body === 'object' && typeof (body as { reason?: unknown }).reason === 'string') {
        reason = (body as { reason: string }).reason.slice(0, 160);
      }
    } catch { /* empty body is fine */ }

    await db.execute(sql`
      UPDATE customers
      SET marketing_opt_out = true,
          opt_out_at = COALESCE(opt_out_at, now()),
          opt_out_reason = COALESCE(opt_out_reason, ${reason ?? 'manual'})
      WHERE id = ${id} AND restaurant_id = ${restaurantId}
    `);
    return NextResponse.json({ ok: true, marketing_opt_out: true });
  })
);

export const DELETE = withErrorHandler(
  withAuth(async (req: AuthedRequest, ctx: RouteContext) => {
    const restaurantId = req.session.restaurantId!;
    const { id } = await ctx.params;
    await ensureCustomerExists(id, restaurantId);
    await db.execute(sql`
      UPDATE customers
      SET marketing_opt_out = false, opt_out_at = NULL, opt_out_reason = NULL
      WHERE id = ${id} AND restaurant_id = ${restaurantId}
    `);
    return NextResponse.json({ ok: true, marketing_opt_out: false });
  })
);
