/**
 * WhatsApp credential management — restaurant-owner only, plan-gated.
 *
 *  GET  /api/channels/whatsapp/credentials      List all branches with their config status.
 *  POST /api/channels/whatsapp/credentials      Upsert credentials for a branch.
 *  DELETE /api/channels/whatsapp/credentials?branch_id=...   Disconnect a branch.
 */

import { NextResponse } from 'next/server';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { withAuth, requireSection, AuthedRequest } from '@server/middleware/withAuth';
import {
  listWhatsAppCredentialsForRestaurant,
  upsertWhatsAppCredentials,
  deleteWhatsAppCredentials,
  restaurantHasWhatsAppFeature,
  syncWhatsAppTemplates,
} from '@server/services/whatsapp.service';
import { childLogger } from '@server/logger';
const log = childLogger('api.whatsapp.credentials');

/**
 * WhatsApp credentials are channel-level secrets that can be used to send
 * messages on behalf of the restaurant — only owner/manager (or platform
 * superadmin) may view, create, modify, or delete them. Front-of-house
 * staff roles must be denied access entirely.
 */
function requireAdmin(req: AuthedRequest): NextResponse | null {
  const role = req.session?.role;
  if (role !== 'owner' && role !== 'manager' && role !== 'superadmin') {
    return NextResponse.json(
      { error: 'Owner or manager access required to manage WhatsApp credentials' },
      { status: 403 }
    );
  }
  return null;
}

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    const denied = requireAdmin(req);
    if (denied) return denied;
    await requireSection(req, 'whatsapp');
    const { restaurantId } = req.session;
    if (!restaurantId) return NextResponse.json({ error: 'Restaurant context required' }, { status: 400 });
    const has = await restaurantHasWhatsAppFeature(restaurantId);
    if (!has) {
      return NextResponse.json(
        { error: 'WhatsApp Business is not included in your plan.', code: 'PLAN_UPGRADE_REQUIRED' },
        { status: 402 }
      );
    }
    const list = await listWhatsAppCredentialsForRestaurant(restaurantId);
    return NextResponse.json({ branches: list });
  })
);

export const POST = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    const denied = requireAdmin(req);
    if (denied) return denied;
    await requireSection(req, 'whatsapp', 'create');
    const { restaurantId } = req.session;
    if (!restaurantId) return NextResponse.json({ error: 'Restaurant context required' }, { status: 400 });

    const has = await restaurantHasWhatsAppFeature(restaurantId);
    if (!has) {
      return NextResponse.json(
        { error: 'WhatsApp Business is not included in your plan. Upgrade to Growth or Pro to enable it.', code: 'PLAN_UPGRADE_REQUIRED' },
        { status: 402 }
      );
    }

    const body = await req.json().catch(() => ({})) as Record<string, unknown>;
    const branchId = typeof body.branch_id === 'string' ? body.branch_id : '';
    if (!branchId) return NextResponse.json({ error: 'branch_id is required' }, { status: 400 });

    try {
      const saved = await upsertWhatsAppCredentials(restaurantId, branchId, {
        phone_number_id: String(body.phone_number_id ?? '').trim(),
        waba_id: typeof body.waba_id === 'string' ? body.waba_id : null,
        whatsapp_phone_number: typeof body.whatsapp_phone_number === 'string' ? body.whatsapp_phone_number : null,
        display_name: typeof body.display_name === 'string' ? body.display_name : null,
        access_token: typeof body.access_token === 'string' ? body.access_token : undefined,
        app_secret: typeof body.app_secret === 'string' ? body.app_secret : undefined,
        is_active: typeof body.is_active === 'boolean' ? body.is_active : undefined,
      });

      // Background template sync — best-effort, non-blocking.
      // Only triggered when a WABA ID is present (required by the Graph API).
      // Both resolved failures ({ ok: false }) and thrown exceptions are
      // logged at WARN level; neither is surfaced to the operator — the
      // manual "Sync from Meta" button in the Campaign wizard is the fallback.
      if (saved.waba_id) {
        syncWhatsAppTemplates(restaurantId, branchId).then((res) => {
          if (!res.ok) {
            log.warn({ error: res.error, branchId }, 'WhatsApp auto-sync failed after credential save');
          }
        }).catch((err) => {
          log.warn({ err, branchId }, 'WhatsApp auto-sync threw after credential save');
        });
      }

      return NextResponse.json({ credential: saved });
    } catch (err) {
      const msg = err instanceof Error ? err.message : 'Failed to save credentials';
      return NextResponse.json({ error: msg }, { status: 400 });
    }
  })
);

export const DELETE = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    const denied = requireAdmin(req);
    if (denied) return denied;
    await requireSection(req, 'whatsapp', 'delete');
    const { restaurantId } = req.session;
    if (!restaurantId) return NextResponse.json({ error: 'Restaurant context required' }, { status: 400 });
    const url = new URL(req.url);
    const branchId = url.searchParams.get('branch_id');
    if (!branchId) return NextResponse.json({ error: 'branch_id is required' }, { status: 400 });
    await deleteWhatsAppCredentials(restaurantId, branchId);
    return NextResponse.json({ ok: true });
  })
);
