import { NextResponse } from 'next/server';
import { getDb } from '@/lib/db';

export const dynamic = 'force-dynamic';

interface PhoneGatewayConfig {
  host: string;
  port: string;
  username: string;
  password?: string;
  label?: string;
  mode: 'local' | 'cloud';
  apiUrl?: string;
}

export async function POST(request: Request) {
  try {
    const body = await request.json() as PhoneGatewayConfig;
    const { host, port, username, password, label, mode, apiUrl } = body;

    if (!host || !port) {
      return NextResponse.json({ success: false, error: 'Host and port are required' }, { status: 400 });
    }

    const db = getDb();
    const config = {
      host,
      port,
      username,
      // Don't save password in plaintext, just store that config exists
      label: label || 'Android Phone',
      mode,
      apiUrl: apiUrl || null,
      updatedAt: new Date().toISOString(),
    };

    // Store as JSON in settings table
    db.prepare(`
      INSERT OR REPLACE INTO settings (key, value, updated_at)
      VALUES (?, ?, ?)
    `).run('phone_gateway_config', JSON.stringify(config), new Date().toISOString());

    return NextResponse.json({ success: true, config });
  } catch (error: any) {
    console.error('Failed to save phone gateway config:', error);
    return NextResponse.json(
      { success: false, error: 'Failed to save configuration' },
      { status: 500 }
    );
  }
}
