/**
 * WhatsApp template cache — per-branch sync & list.
 *
 *  GET  /api/channels/whatsapp/templates?branch_id=...
 *       Returns { connected: bool, templates: [...] }.
 *       connected=false when the branch has no WhatsApp credentials/WABA ID.
 *
 *  POST /api/channels/whatsapp/templates
 *       { branch_id } — syncs from Meta Graph API then returns updated list.
 */

import { NextResponse } from 'next/server';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { withAuth, AuthedRequest } from '@server/middleware/withAuth';
import {
  syncWhatsAppTemplates,
  listWhatsAppTemplates,
  getBranchCredsByBranchId,
} from '@server/services/whatsapp.service';

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    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 });
    }

    // Explicit credential check — the template list alone cannot distinguish
    // "no credentials" from "credentials exist but no templates synced yet".
    const creds = await getBranchCredsByBranchId(branchId);
    const connected = Boolean(creds && creds.restaurantId === restaurantId && creds.wabaId);
    if (!connected) {
      return NextResponse.json({ connected: false, templates: [] });
    }

    const result = await listWhatsAppTemplates(restaurantId, branchId);
    if (!result.ok) {
      return NextResponse.json({ error: result.error }, { status: 500 });
    }
    return NextResponse.json({ connected: true, templates: result.templates });
  })
);

export const POST = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    const { restaurantId } = req.session;
    if (!restaurantId) {
      return NextResponse.json({ error: 'Restaurant context required' }, { status: 400 });
    }
    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 });
    }
    const result = await syncWhatsAppTemplates(restaurantId, branchId);
    if (!result.ok) {
      return NextResponse.json({ error: result.error }, { status: 422 });
    }
    return NextResponse.json({ templates: result.templates });
  })
);
