import { NextResponse } from 'next/server';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { withAuth, requireSection } from '@server/middleware/withAuth';
import { withValidationAuthed } from '@server/middleware/withValidation';
import { z } from 'zod';
import { db } from '@server/db/drizzle';
import { sql } from 'drizzle-orm';
import { initiateOutboundCall } from '@server/services/telephone/twilio-phone.service';
import { requirePlanFeature, getPlanLimits } from '@server/utils/features';

const outboundSchema = z.object({
  to: z.string().min(1),
  from_number_id: z.string().uuid(),
});

export const POST = withErrorHandler(
  withAuth(
    withValidationAuthed(outboundSchema, async (req) => {
      const { to, from_number_id } = req.parsedBody as { to: string; from_number_id: string };
      const restaurantId = req.session.restaurantId!;

      await requireSection(req, 'telephone', 'create');
      await requirePlanFeature(restaurantId, 'voice_agent');

      // Check concurrent voice call limit
      const limits = await getPlanLimits(restaurantId);
      if (limits.concurrent_voice_calls !== null) {
        const { rows: activeRows } = await db.execute(sql`
          SELECT COUNT(*) AS count FROM sip_call_sessions
          WHERE restaurant_id = ${restaurantId} AND status = 'active'
        `);
        const activeCount = parseInt((activeRows[0] as { count: string }).count, 10);
        if (activeCount >= limits.concurrent_voice_calls) {
          return NextResponse.json(
            {
              error: `Your plan allows a maximum of ${limits.concurrent_voice_calls} concurrent voice call${limits.concurrent_voice_calls === 1 ? '' : 's'}. Upgrade to increase this limit.`,
              code: 'PLAN_LIMIT_EXCEEDED',
            },
            { status: 429 }
          );
        }
      }

      // Look up provider so we can route to the right outbound dialer.
      // SIP-routed numbers go through the jambonz add-on (Task #312); all
      // others stay on the existing Twilio path.
      /* raw: SELECT provider FROM phone_numbers WHERE id = $1 AND restaurant_id = $2 LIMIT 1 */
      const { rows } = await db.execute(sql`SELECT provider FROM phone_numbers WHERE id = ${from_number_id} AND restaurant_id = ${restaurantId} LIMIT 1`);
      const provider = (rows[0] as { provider?: string } | undefined)?.provider || 'twilio';

      if (provider === 'sip') {
        const { initiateSipOutboundCall } = await import('@server/engine/sip/outbound');
        const result = await initiateSipOutboundCall(restaurantId, to, from_number_id);
        return NextResponse.json({ success: true, ...result });
      }

      const result = await initiateOutboundCall(restaurantId, to, from_number_id);
      return NextResponse.json({ success: true, ...result });
    })
  )
);
